0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Pairs with Given Sum

You can find pairs with a given sum in JavaScript by using a loop and a Set to track complements, like this: function findPairs(arr, sum) { const seen = new Set(); const pairs = []; for (const num of arr) { const complement = sum - num; if (seen.has(complement)) { pairs.push([complement, num]); } seen.add(num); } return pairs; }
📋

Examples

Input[1, 2, 3, 4, 5], sum = 5
Output[[2, 3], [1, 4]]
Input[0, -1, 2, -3, 1], sum = -2
Output[[-3, 1]]
Input[1, 1, 1, 1], sum = 2
Output[[1, 1], [1, 1], [1, 1]]
🧠

How to Think About It

To find pairs that add up to a given sum, think about each number and what other number it needs to reach that sum. Keep track of numbers you've seen so far. When you find a number whose needed partner is already seen, you have a pair.
📐

Algorithm

1
Create an empty set to store numbers seen so far.
2
Create an empty list to store pairs found.
3
For each number in the array:
4
Calculate the complement by subtracting the number from the target sum.
5
If the complement is in the set, add the pair to the list.
6
Add the current number to the set.
7
Return the list of pairs.
💻

Code

javascript
function findPairs(arr, sum) {
  const seen = new Set();
  const pairs = [];
  for (const num of arr) {
    const complement = sum - num;
    if (seen.has(complement)) {
      pairs.push([complement, num]);
    }
    seen.add(num);
  }
  return pairs;
}

const array = [1, 2, 3, 4, 5];
const targetSum = 5;
console.log(findPairs(array, targetSum));
Output
[[2,3],[1,4]]
🔍

Dry Run

Let's trace the example array [1, 2, 3, 4, 5] with sum 5 through the code.

1

Start with empty set and pairs

seen = {}, pairs = []

2

Process number 1

complement = 5 - 1 = 4; 4 not in seen; add 1 to seen; seen = {1}

3

Process number 2

complement = 5 - 2 = 3; 3 not in seen; add 2 to seen; seen = {1, 2}

4

Process number 3

complement = 5 - 3 = 2; 2 in seen; add pair [2, 3]; pairs = [[2, 3]]; add 3 to seen; seen = {1, 2, 3}

5

Process number 4

complement = 5 - 4 = 1; 1 in seen; add pair [1, 4]; pairs = [[2, 3], [1, 4]]; add 4 to seen; seen = {1, 2, 3, 4}

6

Process number 5

complement = 5 - 5 = 0; 0 not in seen; add 5 to seen; seen = {1, 2, 3, 4, 5}

7

Return pairs

pairs = [[2, 3], [1, 4]]

NumberComplementComplement in seen?PairsSeen Set
14No[]{1}
23No[]{1, 2}
32Yes[[2, 3]]{1, 2, 3}
41Yes[[2, 3], [1, 4]]{1, 2, 3, 4}
50No[[2, 3], [1, 4]]{1, 2, 3, 4, 5}
💡

Why This Works

Step 1: Track seen numbers

We use a Set to remember numbers we have already checked, so we can quickly find if the needed partner exists.

Step 2: Find complement

For each number, we calculate the complement by subtracting it from the target sum to know what number pairs with it.

Step 3: Check and store pairs

If the complement is already in the set, we add the pair to the result because together they make the target sum.

🔄

Alternative Approaches

Brute Force Nested Loops
javascript
function findPairsBruteForce(arr, sum) {
  const pairs = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] + arr[j] === sum) {
        pairs.push([arr[i], arr[j]]);
      }
    }
  }
  return pairs;
}

console.log(findPairsBruteForce([1,2,3,4,5], 5));
Simple but slow for large arrays because it checks every pair.
Sorting and Two Pointers
javascript
function findPairsTwoPointers(arr, sum) {
  arr.sort((a, b) => a - b);
  const pairs = [];
  let left = 0, right = arr.length - 1;
  while (left < right) {
    const currentSum = arr[left] + arr[right];
    if (currentSum === sum) {
      pairs.push([arr[left], arr[right]]);
      left++;
      right--;
    } else if (currentSum < sum) {
      left++;
    } else {
      right--;
    }
  }
  return pairs;
}

console.log(findPairsTwoPointers([1,2,3,4,5], 5));
Efficient for sorted arrays but requires sorting first.

Complexity: O(n) time, O(n) space

Time Complexity

The main approach loops through the array once, checking and adding to a set in constant time, so it runs in O(n) time.

Space Complexity

It uses extra space for the set and pairs list, which can grow up to O(n) in the worst case.

Which Approach is Fastest?

The set-based approach is faster than brute force (O(n^2)) and avoids sorting overhead, making it best for unsorted arrays.

ApproachTimeSpaceBest For
Set LookupO(n)O(n)Unsorted arrays, fast lookup
Brute ForceO(n^2)O(1)Very small arrays or simple code
Two PointersO(n log n)O(1)Sorted arrays or when sorting is cheap
💡
Use a Set to track seen numbers for fast lookup when finding pairs with a given sum.
⚠️
Beginners often forget to check if the complement exists before adding the current number to the set, missing valid pairs.