Javascript Program to Count Pairs with Given Sum

To count pairs with given sum is a common problem asked in job interviews and is often used in many real-world applications such as cryptography and data compression.

In this article we are having an array and a target sum value, our task is to write a JavaScript program to count pairs with given sum.

Array: [1, 2, 3, 5, 6, 7, 9] Target Sum: 8 1 2 3 5 6 7 9 Valid Pairs (sum = 8): 1 + 7 = 8 2 + 6 = 8 3 + 5 Total Count: 3

Example

Input:
arr = [1, 2, 3, 5, 6, 7, 9]
sum = 8

Pairs = (1, 7), (2, 6), (3, 5)
Output:
Count: 3

Approaches to Count Pairs with Given Sum

Here are three approaches to count pairs with given sum in JavaScript, each with different time and space complexities:

Using Brute Force

The brute force approach checks all possible pairs by using nested loops. For each element, it pairs it with every other element that comes after it and checks if their sum equals the target.

Example

let arr = [1, 2, 3, 5, 6, 7, 9];
let sum = 8;

function countPair(array, sum) {
    let counter = 0;
    for (let i = 0; i < array.length; i++) {
        for (let j = i + 1; j < array.length; j++) {
            if (array[i] + array[j] === sum) {
                console.log(`Pair found: (${array[i]}, ${array[j]})`);
                counter++;
            }
        }
    }
    return counter;
}

console.log("Number of pairs with sum " + sum + " is: " + countPair(arr, sum));
Pair found: (1, 7)
Pair found: (2, 6)
Pair found: (3, 5)
Number of pairs with sum 8 is: 3

Using Two Pointers

The two pointers technique works on sorted arrays. It uses one pointer at the start and another at the end, moving them based on the sum comparison.

Example

let arr = [1, 2, 3, 5, 6, 7, 9];
let sum = 8;

function countPair(array, sum) {
    array.sort((a, b) => a - b);
    let left = 0;
    let right = array.length - 1;
    let count = 0;
    
    while (left < right) {
        const currSum = array[left] + array[right];
        if (currSum === sum) {
            console.log(`Pair found: (${array[left]}, ${array[right]})`);
            count++;
            left++;
            right--;
        } else if (currSum < sum) {
            left++;
        } else {
            right--;
        }
    }
    return count;
}

console.log("Number of pairs with sum " + sum + " is: " + countPair(arr, sum));
Pair found: (1, 7)
Pair found: (2, 6)
Pair found: (3, 5)
Number of pairs with sum 8 is: 3

Using Hash Map

The hash map approach stores element frequencies and checks for complements. For each element, it looks for (target - element) in the hash map.

How It Works

Example with arr = [1, 2, 3, 4], sum = 4:

Step 1: Build hash map
{1: 1, 2: 1, 3: 1, 4: 1}

Step 2: Check complements
- Element 1: Look for (4-1=3) ? Found! count++
- Element 2: Look for (4-2=2) ? Found! count++  
- Element 3: Look for (4-3=1) ? Found! count++
- Element 4: Look for (4-4=0) ? Not found

Step 3: Return count/2 (to avoid double counting)
Result: 3/2 = 1 pair

Example

let arr = [1, 2, 3, 5, 6, 7, 9];
let sum = 8;

function countPair(array, sum) {
    let count = 0;
    let hash_map = {};
    
    // Build frequency map
    for (let i = 0; i < array.length; i++) {
        hash_map[array[i]] = (hash_map[array[i]] || 0) + 1;
    }
    
    // Count pairs
    for (let i = 0; i < array.length; i++) {
        const complement = sum - array[i];
        if (hash_map[complement]) {
            count += hash_map[complement];
            
            // If element pairs with itself, subtract 1
            if (complement === array[i]) {
                count--;
            }
        }
    }
    
    return Math.floor(count / 2);
}

console.log("Number of pairs with sum " + sum + " is: " + countPair(arr, sum));
Number of pairs with sum 8 is: 3

Complexity Comparison

Approach Time Complexity Space Complexity Best For
Brute Force O(n²) O(1) Small arrays
Two Pointers O(n log n) O(1) When sorting is acceptable
Hash Map O(n) O(n) Large arrays, optimal performance

Conclusion

The hash map approach offers the best time complexity O(n) for counting pairs with a given sum, making it ideal for large datasets. The two pointers technique provides a good balance with O(n log n) time and O(1) space, while brute force is suitable only for small arrays due to its O(n²) complexity.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements