Given an array of integers, find the two numbers such that they add up to a specific target

problemsolving
Published

July 21, 2024

Finding Two Numbers That Add Up to a Target in JavaScript

This blog post explores how to efficiently solve a common coding problem: given an array of integers, find the two numbers within that array that add up to a specific target. We’ll cover many approaches in JavaScript, ranging from brute-force to optimized solutions.

Brute-Force Approach

The simplest, albeit least efficient, method involves a nested loop. This approach checks every possible pair of numbers in the array.

function findSumBruteForce(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 [nums[i], nums[j]];
      }
    }
  }
  return null; // No pair found
}

let nums = [2, 7, 11, 15];
let target = 9;
let result = findSumBruteForce(nums, target);
console.log(result); // Output: [2, 7]

This approach has a time complexity of O(n²), making it inefficient for large arrays.

Using a Hash Map (Object)

A more efficient solution utilizes a hash map (JavaScript object) to store numbers and their indices. This reduces the time complexity to O(n).

function findSumHashMap(nums, target) {
  const numMap = {}; // Create a hash map

  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (complement in numMap) {
      return [nums[i], complement];
    }
    numMap[nums[i]] = i; // Store the number and its index
  }
  return null; // No pair found
}

nums = [2, 7, 11, 15];
target = 9;
result = findSumHashMap(nums, target);
console.log(result); // Output: [2, 7]

This method iterates through the array only once, checking if the complement of the current number exists in the hash map. If it does, we’ve found our pair. If not, we add the current number and its index to the map for later lookup.

Handling Edge Cases

Consider edge cases such as empty arrays or arrays where no pair sums to the target. The code examples above handle these by returning null. You might choose to throw an error or return a different value depending on your specific requirements. For example, you could modify the findSumHashMap function like this to explicitly handle an empty array:

function findSumHashMap(nums, target) {
  if (nums.length === 0) {
    return []; //Return an empty array for empty input
  }
  const numMap = {}; 
  // ...rest of the function remains the same
}

Remember to choose the approach that best suits your needs based on the size of your input data and performance requirements. The hash map approach is generally preferred for its efficiency.