2 Sum - Count pairs with given sum
Given an array arr[] of n integers and a target value, the task is to find the number of pairs of integers in the array whose sum is equal to target.
Examples:
Input: arr[] = {1, 5, 7, -1, 5}, target = 6
Output: 3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5).Input: arr[] = {1, 1, 1, 1}, target = 2
Output: 6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1) and (1, 1).Input: arr[] = {10, 12, 10, 15, -1}, target = 125
Output: 0
Table of Content
[Naive Approach] By Generating all Possible Pairs - O(n^2) time and O(1) space
The very basic approach is to generate all the possible pairs and check if any pair exists whose sum is equals to given target value, then increment the count variable.
// C++ Program to count pairs with given sum by
// generating all possible pairs
#include <iostream>
#include <vector>
using namespace std;
// Function to count all pairs whose sum is equal
// to the given target value
int countPairs(vector<int> &arr, int target) {
int n = arr.size();
int cnt = 0;
// Iterate through each element in the array
for (int i = 0; i < n; i++) {
// For each element arr[i], check every
// other element arr[j] that comes after it
for (int j = i + 1; j < n; j++) {
// Check if the sum of the current pair
// equals the target
if (arr[i] + arr[j] == target) {
cnt++;
}
}
}
return cnt;
}
int main() {
vector<int> arr = {1, 5, 7, -1, 5};
int target = 6;
cout << countPairs(arr, target) << endl;
return 0;
}
// C Program to count pairs with given sum by
// generating all possible pairs
#include <stdio.h>
int countPairs(int arr[], int n, int target) {
int cnt = 0;
// Iterate through each element in the array
for (int i = 0; i < n; i++) {
// For each element arr[i], check every
// other element arr[j] that comes after it
for (int j = i + 1; j < n; j++) {
// Check if the sum of the current pair
// equals the target
if (arr[i] + arr[j] == target) {
cnt++;
}
}
}
return cnt;
}
int main() {
int arr[] = {1, 5, 7, -1, 5};
int target = 6;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", countPairs(arr, n, target));
return 0;
}
// Java Program to count pairs with given sum by
// generating all possible pairs
import java.util.Arrays;
class GfG {
// Function to count all pairs whose sum is equal
// to the given target value
static int countPairs(int[] arr, int target) {
int n = arr.length;
int cnt = 0;
// Iterate through each element in the array
for (int i = 0; i < n; i++) {
// For each element arr[i], check every
// other element arr[j] that comes after it
for (int j = i + 1; j < n; j++) {
// Check if the sum of the current pair
// equals the target
if (arr[i] + arr[j] == target) {
cnt++;
}
}
}
return cnt;
}
public static void main(String[] args) {
int[] arr = { 1, 5, 7, -1, 5 };
int target = 6;
System.out.println(countPairs(arr, target));
}
}
# Python Program to count pairs with given sum
# by generating all possible pairs
# Function to count all pairs whose sum is equal
# to the given target value
def countPairs(arr, target):
n = len(arr)
cnt = 0
# Iterate through each element in the array
for i in range(n):
# For each element arr[i], check every
# other element arr[j] that comes after it
for j in range(i + 1, n):
# Check if the sum of the current pair
# equals the target
if arr[i] + arr[j] == target:
cnt += 1
return cnt
if __name__ == "__main__":
arr = [1, 5, 7, -1, 5]
target = 6
print(countPairs(arr, target))
// C# Program to count pairs with given sum by
// generating all possible pairs
using System;
class GfG {
// Function to count all pairs whose sum is
// equal to the given target value
static int countPairs(int[] arr, int target) {
int n = arr.Length;
int cnt = 0;
// Iterate through each element in the array
for (int i = 0; i < n; i++) {
// For each element arr[i], check every
// other element arr[j] that comes after it
for (int j = i + 1; j < n; j++) {
// Check if the sum of the current pair
// equals the target
if (arr[i] + arr[j] == target) {
cnt++;
}
}
}
return cnt;
}
static void Main() {
int[] arr = { 1, 5, 7, -1, 5 };
int target = 6;
Console.WriteLine(countPairs(arr, target));
}
}
// JavaScript Program to count pairs with given sum by
// generating all possible pairs
// Function to count all pairs whose sum is equal
// to the given target value
function countPairs(arr, target) {
const n = arr.length;
let cnt = 0;
// Iterate through each element in the array
for (let i = 0; i < n; i++) {
// For each element arr[i], check every
// other element arr[j] that comes after it
for (let j = i + 1; j < n; j++) {
// Check if the sum of the current pair
// equals the target
if (arr[i] + arr[j] === target)
cnt++;
}
}
return cnt;
}
const arr = [1, 5, 7, -1, 5];
const target = 6;
console.log(countPairs(arr, target));
Output
3
[Better Approach] Using Two Pointers Technique - O(nlogn) Time and O(1) Space
The idea is to sort the input array and use two-pointer technique. Maintain two pointers, say left and right and initialize them to the first and last element of the array respectively. According to the sum of left and right pointers, we can have three cases:
- arr[left] + arr[right] < target: Increase the pair sum by moving the left pointer towards right.
- arr[left] + arr[right] > target: Decrease the pair sum by moving the right pointer towards left.
- arr[left] + arr[right] = target: We have found a pair whose sum is equal to target. We can find the product of the count of both the elements and add them to the result.
To know more about the implementation, please refer 2 Sum – Count Pairs with given Sum in Sorted Array.
[Expected Approach] Using Hash Map or Dictionary - O(n) Time and O(n) Space
HashMap or Dictionary provides a more efficient solution to the 2Sum problem. Instead of checking every pair of numbers, we keep each number in a map as we go through the array. For each number, we calculate its complement (i.e., target - current number) and check if it’s in the map. If it is, increment the count variable by the occurrences of complement in map.
// C++ Program to count pairs with given sum
// using Hash Map
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
// Returns number of pairs in arr[0...n-1] with sum
// equal to 'target'
int countPairs(vector<int>& arr, int target) {
unordered_map<int, int> freq;
int cnt = 0;
for (int i = 0; i < arr.size(); i++) {
// Check if the complement (target - arr[i])
// exists in the map. If yes, increment count
if (freq.find(target - arr[i]) != freq.end()) {
cnt += freq[target - arr[i]];
}
// Increment the frequency of arr[i]
freq[arr[i]]++;
}
return cnt;
}
int main() {
vector<int> arr = {1, 5, 7, -1, 5};
int target = 6;
cout << countPairs(arr, target);
return 0;
}
// Java Program to count pairs with given sum
// using Hash Map
import java.util.Map;
import java.util.HashMap;
class GfG {
// Returns number of pairs in arr[0...n-1] with
// sum equal to 'target'
static int countPairs(int[] arr, int target) {
Map<Integer, Integer> freq = new HashMap<>();
int cnt = 0;
for (int i = 0; i < arr.length; i++) {
// Check if the complement (target - arr[i])
// exists in the map. If yes, increment count
if (freq.containsKey(target - arr[i])) {
cnt += freq.get(target - arr[i]);
}
// Increment the frequency of arr[i]
freq.put(arr[i],
freq.getOrDefault(arr[i], 0) + 1);
}
return cnt;
}
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int target = 6;
System.out.println(countPairs(arr, target));
}
}
# Python Program to count pairs with given sum
# using Dictionary
# Returns number of pairs in arr[0...n-1] with sum
# equal to 'target'
def countPairs(arr, target):
freq = {}
cnt = 0
for i in range(len(arr)):
# Check if the complement (target - arr[i])
# exists in the map. If yes, increment count
if (target - arr[i]) in freq:
cnt += freq[target - arr[i]]
# Increment the frequency of arr[i]
freq[arr[i]] = freq.get(arr[i], 0) + 1
return cnt
if __name__ == "__main__":
arr = [1, 5, 7, -1, 5]
target = 6
print(countPairs(arr, target))
// C# Program to count pairs with given sum using Hash Map
using System;
using System.Collections.Generic;
class GfG {
// Returns number of pairs in arr[0...n-1] with sum
// equal to 'target'
static int countPairs(int[] arr, int target) {
Dictionary<int, int> freq =
new Dictionary<int, int>();
int cnt = 0;
for (int i = 0; i < arr.Length; i++) {
// Check if the complement (target - arr[i])
// exists in the map. If yes, increment count
if (freq.ContainsKey(target - arr[i])) {
cnt += freq[target - arr[i]];
}
// Increment the frequency of arr[i]
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
return cnt;
}
public static void Main() {
int[] arr = { 1, 5, 7, -1, 5 };
int target = 6;
Console.WriteLine(countPairs(arr, target));
}
}
// JavaScript Program to count pairs with given sum
// using Hash Map
// Returns number of pairs in arr[0...n-1] with sum
// equal to 'target'
function countPairs(arr, target) {
const freq = new Map();
let cnt = 0;
for (let i = 0; i < arr.length; i++) {
// Check if the complement (target - arr[i])
// exists in the map. If yes, increment count
if (freq.has(target - arr[i])) {
cnt += freq.get(target - arr[i]);
}
// Increment the frequency of arr[i]
freq.set(arr[i], (freq.get(arr[i]) || 0) + 1);
}
return cnt;
}
const arr = [1, 5, 7, -1, 5];
const target = 6;
console.log(countPairs(arr, target));
Output
3
Related Problems: