Given an array of N integers, and an integer K, the task is to find the number of pairs of integers in the array whose sum is equal to K.
Examples:
Input: arr[] = {1, 5, 7, -1}, K = 6
Output: 2
Explanation: Pairs with sum 6 are (1, 5) and (7, -1).
Input: arr[] = {1, 5, 7, -1, 5}, K = 6
Output: 3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5).
Input: arr[] = {1, 1, 1, 1}, K = 2
Output: 6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1).
Input: arr[] = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}, K = 11
Output: 9
Explanation: Pairs with sum 11 are (10, 1), (10, 1), (10, 1), (12, -1), (10, 1), (10, 1), (10, 1), (7, 4), (6, 5).
Naïve Approach:
A simple solution is to user nested loops, one for traversal of each element and other for checking if there’s another number in the array which can be added to it to give K.
Illustration:
Consider an array arr [ ] = {1 ,5 ,7 ,1} and K = 6
- initialize count = 0
- First iteration
- i = 0
- j = 1
- arr[i]+arr[j] == K
- count = 1
- i = 0
- j = 2
- arr[i] + arr[j] != K
- count = 1
- i = 0
- j = 3
- arr[i] + arr[j] != K
- count = 1
- Second iteration
- i = 1
- j = 2
- arr[i] + arr[j] != K
- count = 1
- i = 1
- j = 3
- arr[i] + arr[j] == K
- count = 2
- Third iteration
- i = 2
- j = 3
- arr[i] + arr[j] != K
- count = 2
- Hence Output is 2 .
Follow the steps below to solve the given problem:
Follow the steps below for implementation:
- Initialize the count variable with 0 which stores the result.
- Use two nested loop and check if arr[i] + arr[j] == K, then increment the count variable.
- Return the count.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int getPairsCount( int arr[], int n, int K)
{
int count = 0;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == K)
count++;
return count;
}
int main()
{
int arr[] = { 1, 5, 7, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
int K = 6;
cout << "Count of pairs is "
<< getPairsCount(arr, n, K);
return 0;
}
|
C
#include <stdio.h>
int getPairsCount( int arr[], int n, int K)
{
int count = 0;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == K)
count++;
return count;
}
int main()
{
int arr[] = { 1, 5, 7, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
int K = 6;
printf ( "Count of pairs is %d" ,
getPairsCount(arr, n, K));
return 0;
}
|
Java
public class find {
public static void main(String args[])
{
int [] arr = { 1 , 5 , 7 , - 1 , 5 };
int K = 6 ;
getPairsCount(arr, K);
}
public static void getPairsCount( int [] arr, int K)
{
int count = 0 ;
for ( int i = 0 ; i < arr.length; i++)
for ( int j = i + 1 ; j < arr.length; j++)
if ((arr[i] + arr[j]) == K)
count++;
System.out.printf( "Count of pairs is %d" , count);
}
}
|
Python3
def getPairsCount(arr, n, K):
count = 0
for i in range ( 0 , n):
for j in range (i + 1 , n):
if arr[i] + arr[j] = = K:
count + = 1
return count
arr = [ 1 , 5 , 7 , - 1 ]
n = len (arr)
K = 6
print ( "Count of pairs is" ,
getPairsCount(arr, n, K))
|
C#
using System;
class GFG {
public static void getPairsCount( int [] arr, int sum)
{
int count = 0;
for ( int i = 0; i < arr.Length; i++)
for ( int j = i + 1; j < arr.Length; j++)
if ((arr[i] + arr[j]) == sum)
count++;
Console.WriteLine( "Count of pairs is " + count);
}
static public void Main()
{
int [] arr = { 1, 5, 7, -1, 5 };
int sum = 6;
getPairsCount(arr, sum);
}
}
|
Javascript
<script>
function getPairsCount(arr, n, sum)
{
let count = 0;
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
count++;
return count;
}
let arr = [ 1, 5, 7, -1, 5 ];
let n = arr.length;
let sum = 6;
document.write( "Count of pairs is "
+ getPairsCount(arr, n, sum));
</script>
|
PHP
<?php
function getPairsCount( $arr , $n , $sum )
{
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
if ( $arr [ $i ] + $arr [ $j ] == $sum )
$count ++;
return $count ;
}
$arr = array (1, 5, 7, -1, 5) ;
$n = sizeof( $arr );
$sum = 6;
echo "Count of pairs is "
, getPairsCount( $arr , $n , $sum );
?>
|
Output
Count of pairs is 2
Time Complexity: O(n2), traversing the array for each element
Auxiliary Space: O(1)
Count pairs with given sum using Binary Search.
If the array is sorted then for each array element , we can find the number of pairs by searching all the values (K – arr[i]) which are situated after ith index using Binary Search.
Illustration:
Given arr[ ] = {1, 5, 7, -1} and K = 6
- sort the array = {-1,1,5,7}
- initialize count = 0
- At index = 0:
- val = K – arr[0] = 6 – (-1) = 7
- count = count + upperBound(1, 3, 7) – lowerBound(1, 3, 7)
- count = 1
- At index = 1:
- val = K – arr[1] = 6 – 1 = 5
- count = count + upperBound(2, 3, 5) – lowerBound(2, 3, 5)
- count = 2
- At index = 2:
- val = K – arr[2] = 6 – 5 = 1
- count = count + upperBound(3, 3, 1) – lowerBound(3, 3, 1)
- count = 2
- Number of pairs = 2
Follow the steps below to solve the given problem:
- Sort the array arr[] in increasing order.
- Loop from i = 0 to N-1.
- Find the index of the first element having value same or just greater than (K – arr[i]) using lower bound.
- Find the index of the first element having value just greater than (K – arr[i]) using upper bound.
- The gap between these two indices is the number of elements with value same as (K – arr[i]).
- Add this with the final count of pairs.
- Return the final count after the iteration is over.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int getPairsCount( int arr[], int n, int k)
{
sort(arr, arr + n);
int x = 0, c = 0, y, z;
for ( int i = 0; i < n - 1; i++) {
x = k - arr[i];
int y = lower_bound(arr + i + 1, arr + n, x) - arr;
int z = upper_bound(arr + i + 1, arr + n, x) - arr;
c = c + z - y;
}
return c;
}
int main()
{
int arr[] = { 1, 5, 7, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 6;
cout << "Count of pairs is "
<< getPairsCount(arr, n, k);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int lowerBound( int [] arr, int start,
int end, int key)
{
while (start < end) {
int mid = start + (end - start) / 2 ;
if (arr[mid] < key) {
start = mid + 1 ;
}
else {
end = mid;
}
}
return start;
}
public static int upperBound( int [] arr, int start,
int end, int key)
{
while (start < end) {
int mid = start + (end - start) / 2 ;
if (arr[mid] <= key) {
start = mid + 1 ;
}
else {
end = mid;
}
}
return start;
}
public static int getPairsCount( int [] arr, int n, int k)
{
Arrays.sort(arr);
int c = 0 ;
for ( int i = 0 ; i < n - 1 ; i++) {
int x = k - arr[i];
int y = lowerBound(arr, i + 1 , n, x);
int z = upperBound(arr, i + 1 , n, x);
c = c + z - y;
}
return c;
}
public static void main(String[] args)
{
int [] arr = { 1 , 5 , 7 , - 1 };
int n = arr.length;
int k = 6 ;
System.out.println( "Count of pairs is "
+ getPairsCount(arr, n, k));
}
}
|
Python3
import bisect
def getPairsCount(arr, n, k):
arr.sort()
x, c = 0 , 0
for i in range (n - 1 ):
x = k - arr[i]
y = bisect.bisect_left(arr, x, i + 1 , n)
z = bisect.bisect(arr, x, i + 1 , n)
c = c + z - y
return c
arr = [ 1 , 5 , 7 , - 1 ]
n = len (arr)
k = 6
print ( "Count of pairs is" , getPairsCount(arr, n, k))
|
C#
using System;
using System.Collections;
public class GFG {
public static int lowerBound( int [] arr, int start,
int end, int key)
{
while (start < end) {
int mid = start + (end - start) / 2;
if (arr[mid] < key) {
start = mid + 1;
}
else {
end = mid;
}
}
return start;
}
public static int upperBound( int [] arr, int start,
int end, int key)
{
while (start < end) {
int mid = start + (end - start) / 2;
if (arr[mid] <= key) {
start = mid + 1;
}
else {
end = mid;
}
}
return start;
}
public static int getPairsCount( int [] arr, int n, int k)
{
Array.Sort(arr);
int c = 0;
for ( int i = 0; i < n - 1; i++) {
int x = k - arr[i];
int y = lowerBound(arr, i + 1, n, x);
int z = upperBound(arr, i + 1, n, x);
c = c + z - y;
}
return c;
}
static public void Main()
{
int [] arr = { 1, 5, 7, -1};
int n = arr.Length;
int k = 6;
Console.WriteLine( "Count of pairs is "
+ getPairsCount(arr, n, k));
}
}
|
Javascript
function lowerBound(arr, start, end, key) {
while (start < end) {
var mid = start + Math.floor((end - start) / 2);
if (arr[mid] < key) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
function upperBound(arr, start, end, key) {
while (start < end) {
var mid = start + Math.floor((end - start) / 2);
if (arr[mid] <= key) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
function getPairsCount(arr, n, k) {
arr.sort((a, b) => a - b);
var c = 0;
for ( var i = 0; i < n - 1; i++) {
var x = k - arr[i];
var y = lowerBound(arr, i + 1, n, x);
var z = upperBound(arr, i + 1, n, x);
c = c + z - y;
}
return c;
}
var arr = [1, 5, 7, -1];
var n = arr.length;
var k = 6;
console.log( "Count of pairs is " + getPairsCount(arr, n, k));
|
Output
Count of pairs is 2
Time Complexity: O(n * log(n) ), applying binary search on each element
Auxiliary Space: O(1)
Count pairs with given sum using Hashing
- Check the frequency of K – arr[i] in the arr
- This can be achieved using Hashing.
Illustration:
Given arr[] = {1, 5, 7, -1} and K = 6
- initialize count = 0
- At index = 0:
- freq[K – arr[0]] = freq[6 – 1] = freq[5] = 0
- count = 0
- freq[arr[0]] = freq[1] = 1
- At index = 1:
- freq[K – arr[1]] = freq[6 – 5] = freq[1] = 1
- count = 1
- freq[arr[1]] = freq[5] = 1
- At index = 2:
- freq[K – arr[2]] = freq[6 – 7] = freq[-1] = 0
- count = 1
- freq[arr[2]] = freq[7] = 1
- At index = 3:
- freq[K – arr[3]] = freq[6 – (-1)] = freq[7] = 1
- count = 2
- freq[arr[3]] = freq[-1] = 1
Follow the steps below to solve the given problem:
- Create a map to store the frequency of each number in the array.
- Check if (K – arr[i]) is present in the map, if present then increment the count variable by its frequency.
- After traversal is over, return the count.
Below is the implementation of the above idea :
C++
#include <bits/stdc++.h>
using namespace std;
int getPairsCount( int arr[], int n, int k)
{
unordered_map< int , int > m;
int count = 0;
for ( int i = 0; i < n; i++) {
if (m.find(k - arr[i]) != m.end()) {
count += m[k - arr[i]];
}
m[arr[i]]++;
}
return count;
}
int main()
{
int arr[] = { 1, 5, 7, -1};
int n = sizeof (arr) / sizeof (arr[0]);
int sum = 6;
cout << "Count of pairs is "
<< getPairsCount(arr, n, sum);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int getPairsCount( int arr[], int n, int k)
{
HashMap<Integer, Integer> m = new HashMap<>();
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (m.containsKey(k - arr[i])) {
count += m.get(k - arr[i]);
}
if (m.containsKey(arr[i])) {
m.put(arr[i], m.get(arr[i]) + 1 );
}
else {
m.put(arr[i], 1 );
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 1 , 5 , 7 , - 1 };
int n = arr.length;
int sum = 6 ;
System.out.print( "Count of pairs is "
+ getPairsCount(arr, n, sum));
}
}
|
Python3
def getPairsCount(arr, n, sum ):
unordered_map = {}
count = 0
for i in range (n):
if sum - arr[i] in unordered_map:
count + = unordered_map[ sum - arr[i]]
if arr[i] in unordered_map:
unordered_map[arr[i]] + = 1
else :
unordered_map[arr[i]] = 1
return count
arr = [ 1 , 5 , 7 , - 1 ]
n = len (arr)
sum = 6
print ( 'Count of pairs is' , getPairsCount(arr, n, sum ))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int getPairsCount( int [] arr, int n, int k)
{
Dictionary< int , int > m = new Dictionary< int , int >();
int count = 0;
for ( int i = 0; i < n; i++) {
if (m.ContainsKey(k - arr[i])) {
count += m[k - arr[i]];
}
if (m.ContainsKey(arr[i])) {
m[arr[i]] = m[arr[i]] + 1;
}
else {
m.Add(arr[i], 1);
}
}
return count;
}
public static void Main(String[] args)
{
int [] arr = { 1, 5, 7, -1 };
int n = arr.Length;
int sum = 6;
Console.Write( "Count of pairs is "
+ getPairsCount(arr, n, sum));
}
}
|
Javascript
<script>
function getPairsCount(arr , n , k) {
var m = new Map();
var count = 0;
for ( var i = 0; i < n; i++) {
if (m.has(k - arr[i])) {
count += m.get(k - arr[i]);
}
if (m.has(arr[i])) {
m.set(arr[i], m.get(arr[i]) + 1);
} else {
m.set(arr[i], 1);
}
}
return count;
}
var arr = [ 1, 5, 7, -1 ];
var n = arr.length;
var sum = 6;
document.write( "Count of pairs is " + getPairsCount(arr, n, sum));
</script>
|
Output
Count of pairs is 2
Time Complexity: O(n), to iterate over the array
Auxiliary Space: O(n), to make a map of size n
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Jul, 2023
Like Article
Save Article