Pair Sum LeetCode Solution in JavaScript

Tech reviewed: Deepak Prasad
Pair Sum LeetCode Solution in JavaScript

The pair sum LeetCode problem is the classic two-sum style challenge: find two indices whose values add up to the target. It is one of the first algorithm problems people use to practice array traversal and hash map lookups.

The simplest solution is brute force, but the faster approach uses a map or object to track numbers you have already seen. If you are comparing array cleanup techniques too, remove duplicates from array JS is a related array problem.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Solve pair sum with brute force

The brute-force approach checks every pair until it finds the target.

javascript
function pairSum(numbers, target) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      if (numbers[i] + numbers[j] === target) {
        return [i, j];
      }
    }
  }
}

console.log("pair-sum:", pairSum([2, 7, 11, 15], 9).join(","));
Output

You should see one line logging pair-sum: 0,1.

Use this when you want the clearest starting point, even though the time complexity is O(n^2).


Method 2: Solve pair sum with a map

A map lets you remember previously seen numbers and check the needed complement immediately.

javascript
function pairSumMap(numbers, target) {
  const seen = new Map();

  for (let i = 0; i < numbers.length; i++) {
    const need = target - numbers[i];
    if (seen.has(need)) {
      return [seen.get(need), i];
    }
    seen.set(numbers[i], i);
  }
}

console.log("pair-sum-map:", pairSumMap([11, 15, 2, 7], 9).join(","));
Output

You should see one line logging pair-sum-map: 2,3.

This approach is O(n) and is the version most interviewers expect.


Method 3: Trace the indices step by step

Logging the indices makes the search path visible.

javascript
function tracePairSum(numbers, target) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      console.log(i, j);
      if (numbers[i] + numbers[j] === target) {
        return [i, j];
      }
    }
  }
}

console.log("pair-trace:", tracePairSum([11, 15, 2, 7], 9).join(","));
Output

You should see 7 lines, in order: 0 1, 0 2, 0 3, 1 2, 1 3, 2 3, pair-trace: 2,3.

This makes the nested-loop search pattern easier to explain and verify.


Summary

The LeetCode pair sum problem in JavaScript can be solved with brute force or with a map. Use brute force to understand the indices, then use a hash map when you want the faster O(n) solution.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital …

  • JavaScript
  • Web Design