Javascript Program to Count pairs with given sum


Counting pairs with a given sum is a common problem in computer science and is often used in many real-world applications such as cryptography and data compression. The problem is to find the number of pairs in an array that have a sum equal to a given value. In this blog post, we will explore different solutions to this problem and their time and space complexities.

Given an array of n integers and a given sum S, find the total number of pairs of elements in the given array with sum is equal to S.

Input

array[]=[2,4,3,1,2,5], S=5 

Output

3

Explanation − In the above array we have 3 pairs (2,3) , (4,1) and (3,2) with a sum of 5.

Input

array[]=[2,4,3,1,2,5], S=4 

Output

2

Explanation − In the above array we have 2 pairs (2,2) , (3,1) with sum equal to 4;

Brute Force Solution

The simplest solution to this problem is to iterate through all pairs of elements in the input array and check if their sum is equal to the given sum. For each pair of elements, we check if their sum is equal to S, and if it is, we increment a counter. Here we will be using nested loops for the purpose.

Example

function countPairsBruteForce(arr, S) {
   let counter = 0;
   for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
         if (arr[i] + arr[j] === S) {
            counter++;
         }
      }
   }
   return counter;
}
let arr= [ 1,2,3,4,5];
console.log("Original Array: " + arr) 
let sum = 5;
console.log("Number of pairs with sum 5: "+ countPairsBruteForce(arr, sum)); 

The time complexity of the above solution is O(n^2) as we are using nested loops in this solution.

The space complexity is O(1) as we are not using any extra space..

Optimized Solution

A more efficient solution to the problem is to use a hash table to store the frequency of each element in the array and then iterating through the array again to find pairs with the given sum.

For each element in the array, we check if the complement of the element (S - element) is in the hash table. If the complement is present, we increment the counter by the frequency of the complement. .

For example −

Let us take the array [1,2,3,4,5] ans sum S=5

Insert every element of the array in the hash with their frequency

hash_table[1]=1
hash_table[2]=1
hash_table[3]=1
hash_table[4]=1
hash_table[5]=1

Initialize a variable to store the count of pairs, let it be count.

For index=0,
if(hash[sum-arr[0]] is present in the hash map, i.e.
if(hash[5-1] is present , increment the counter by the frequency of the element.

Similarly, for other indices

For index=1

hash[5-arr[1]] =hash[5-2] = hash[3] is present in array
So, counter+=1;

For index=2
hash[5-arr[2]] =hash[5-3] = hash[2] is present in array
So, counter+=1;

For index=3
hash[5-arr[3] =hash[5-4] = hash[1] is present in array
So, counter+=1;

For index=4
hash[5-arr[4]] =hash[5-5] = hash[0] is not present in array
Therefore, don't increment the counter.

Now the count we have is double the actual answer as we are counting each pair twice , hence dividing the count variable by 2.

Example

function countPairsOptimized(arr, S) {
   let count = 0;
   let hash_map = {};
   for (let ind = 0; ind < arr.length; ind++) {
      if (!hash_map[arr[ind]]) {
         hash_map[arr[ind]] = 0;
      }
      hash_map[arr[ind]]++;
   }
   for (let i = 0; i < arr.length; i++) {
      if (hash_map[S - arr[i]]) {
         count += hash_map[S - arr[i]];
      }
   }
   return count/2;
}
let array = [ 1,2,3,4,5];
console.log("Original Array: " + array)
let sum = 5; 
console.log("Number of pairs with sum 5: " + countPairsOptimized(array, sum));

This solution has a time complexity of O(n) as we are traversing the array only once. The space complexity is O(n) because we are using hash map;

Conclusion

In this tutorial, we have explored different solutions to the problem of counting pairs with a given sum. The brute force solution has a time complexity of O(n^2) and a space complexity of O(1), while the optimized solution has a time complexity of O(n) and a space complexity of O(n). We hope this blog helped you understand the concept better.

Updated on: 06-Mar-2023

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements