Count pairs with given sum | Set 2

07 Jun, 2022
Given an array arr[] and an integer sum, the task is to find the number of pairs of integers in the array whose sum is equal to sum.Examples:  
Input: arr[] = {1, 5, 7, -1}, sum = 6 Output: 2 Pairs with sum 6 are (1, 5) and (7, -1)Input: arr[] = {1, 5, 7, -1, 5}, sum = 6 Output: 3 Pairs with sum 6 are (1, 5), (7, -1) & (1, 5) Input: arr[] = {1, 1, 1, 1}, sum = 2 Output: 6  
 
Approach: Two Different methods have already been discussed here. Here, a method based on sorting will be discussed.  
Sort the array and take two pointers i and j, one pointer pointing to the start of the array i.e. i = 0 and another pointer pointing to the end of the array i.e. j = n – 1.Greater than the sum then decrement j.Lesser than the sum then increment i.Equals to the sum then count such pairs.
Sort the array and take two pointers i and j, one pointer pointing to the start of the array i.e. i = 0 and another pointer pointing to the end of the array i.e. j = n – 1.
Greater than the sum then decrement j.Lesser than the sum then increment i.Equals to the sum then count such pairs.
Greater than the sum then decrement j.
Lesser than the sum then increment i.
Equals to the sum then count such pairs.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of pairs// from arr[] with the given sumint pairs_count(int arr[], int n, int sum){    // To store the count of pairs    int ans = 0;     // Sort the given array    sort(arr, arr + n);     // Take two pointers    int i = 0, j = n - 1;     while (i < j) {        // If sum is greater        if (arr[i] + arr[j] < sum)            i++;         // If sum is lesser        else if (arr[i] + arr[j] > sum)            j--;         // If sum is equal        else {            // Find the frequency of arr[i]            int x = arr[i], xx = i;            while (i < j and arr[i] == x)                i++;             // Find the frequency of arr[j]            int y = arr[j], yy = j;            while (j >= i and arr[j] == y)                j--;             // If arr[i] and arr[j] are same            // then remove the extra number counted            if (x == y) {                int temp = i - xx + yy - j - 1;                ans += (temp * (temp + 1)) / 2;            }            else                ans += (i - xx) * (yy - j);        }    }     // Return the required answer    return ans;} // Driver codeint main(){    int arr[] = { 1, 5, 7, 5, -1 };    int n = sizeof(arr) / sizeof(arr[0]);    int sum = 6;     cout << pairs_count(arr, n, sum);     return 0;}
//Java implementation of the approachimport java.util.Arrays;import java.io.*; class GFG{     // Function to return the count of pairs// from arr[] with the given sumstatic int pairs_count(int arr[], int n, int sum){    // To store the count of pairs    int ans = 0;     // Sort the given array    Arrays.sort(arr);     // Take two pointers    int i = 0, j = n - 1;     while (i < j)    {                 // If sum is greater        if (arr[i] + arr[j] < sum)            i++;         // If sum is lesser        else if (arr[i] + arr[j] > sum)            j--;         // If sum is equal        else        {                         // Find the frequency of arr[i]            int x = arr[i], xx = i;            while ((i < j ) && (arr[i] == x))                i++;             // Find the frequency of arr[j]            int y = arr[j], yy = j;            while ((j >= i )&& (arr[j] == y))                j--;             // If arr[i] and arr[j] are same            // then remove the extra number counted            if (x == y)            {                int temp = i - xx + yy - j - 1;                ans += (temp * (temp + 1)) / 2;            }            else                ans += (i - xx) * (yy - j);        }    }     // Return the required answer    return ans;} // Driver codepublic static void main (String[] args){    int arr[] = { 1, 5, 7, 5, -1 };    int n = arr.length;    int sum = 6;         System.out.println (pairs_count(arr, n, sum));}} // The code is contributed by ajit..
# Python3 implementation of the approach # Function to return the count of pairs# from arr with the given sumdef pairs_count(arr, n, sum):         # To store the count of pairs    ans = 0     # Sort the given array    arr = sorted(arr)     # Take two pointers    i, j = 0, n - 1     while (i < j):                 # If sum is greater        if (arr[i] + arr[j] < sum):            i += 1         # If sum is lesser        elif (arr[i] + arr[j] > sum):            j -= 1                     # If sum is equal        else:                         # Find the frequency of arr[i]            x = arr[i]            xx = i            while (i < j and arr[i] == x):                i += 1             # Find the frequency of arr[j]            y = arr[j]            yy = j            while (j >= i and arr[j] == y):                j -= 1             # If arr[i] and arr[j] are same            # then remove the extra number counted            if (x == y):                temp = i - xx + yy - j - 1                ans += (temp * (temp + 1)) // 2            else:                ans += (i - xx) * (yy - j)     # Return the required answer    return ans # Driver codearr = [1, 5, 7, 5, -1]n = len(arr)sum = 6 print(pairs_count(arr, n, sum)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System;     class GFG{     // Function to return the count of pairs// from arr[] with the given sumstatic int pairs_count(int []arr,                       int n, int sum){    // To store the count of pairs    int ans = 0;     // Sort the given array    Array.Sort(arr);     // Take two pointers    int i = 0, j = n - 1;     while (i < j)    {                 // If sum is greater        if (arr[i] + arr[j] < sum)            i++;         // If sum is lesser        else if (arr[i] + arr[j] > sum)            j--;         // If sum is equal        else        {                         // Find the frequency of arr[i]            int x = arr[i], xx = i;            while ((i < j) && (arr[i] == x))                i++;             // Find the frequency of arr[j]            int y = arr[j], yy = j;            while ((j >= i) && (arr[j] == y))                j--;             // If arr[i] and arr[j] are same            // then remove the extra number counted            if (x == y)            {                int temp = i - xx + yy - j - 1;                ans += (temp * (temp + 1)) / 2;            }            else                ans += (i - xx) * (yy - j);        }    }     // Return the required answer    return ans;} // Driver codepublic static void Main (String[] args){    int []arr = { 1, 5, 7, 5, -1 };    int n = arr.Length;    int sum = 6;         Console.WriteLine (pairs_count(arr, n, sum));}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach // Function to return the count of pairs// from arr[] with the given sumfunction pairs_count(arr, n, sum){    // To store the count of pairs    let ans = 0;     // Sort the given array    arr.sort();     // Take two pointers    let i = 0, j = n - 1;     while (i < j) {        // If sum is greater        if (arr[i] + arr[j] < sum)            i++;         // If sum is lesser        else if (arr[i] + arr[j] > sum)            j--;         // If sum is equal        else {            // Find the frequency of arr[i]            let x = arr[i], xx = i;            while (i < j && arr[i] == x)                i++;             // Find the frequency of arr[j]            let y = arr[j], yy = j;            while (j >= i && arr[j] == y)                j--;             // If arr[i] and arr[j] are same            // then remove the extra number counted            if (x == y) {                let temp = i - xx + yy - j - 1;                ans += (temp * (temp + 1)) / 2;            }            else                ans += (i - xx) * (yy - j);        }    }     // Return the required answer    return ans;} // Driver code    let arr = [ 1, 5, 7, 5, -1 ];    let n = arr.length;    let sum = 6;     document.write(pairs_count(arr, n, sum)); // This code is contributed by Mayank Tyagi </script>
3
 
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
mohit kumar 29
jit_t
princiraj1992
mayanktyagi1709
subham348
Arrays
Mathematical
Sorting
Arrays
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays