Given an array of integers, arr[] and an integer target. Find number of pairs in arr[] which sums up to target. It is given that the elements of the arr[] are in sorted order.
Note: Pairs should have elements of distinct indexes.
Examples:
Input: arr[] = [-1, 1, 5, 5, 7], target = 6
Output: 3
Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7).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[] = [-1, 10, 10, 12, 15], target = 125
Output: 0
Explanation: There is no such pair which sums up to 125.
In this post, we are counting pairs with given sum when the input array is sorted. To count the pairs when the input array is not sorted, refer to 2 Sum – Count pairs with given sum.
Table of Content
[Naive Approach] By Generating All Possible Pairs - O(n ^ 2) time and O(1) space
The idea is to generate all the possible pairs and check if any pair exists whose sum is equal to given target value.
- Initialize a variable count to store the number of valid pairs.
- Traverse the array using the first index i.
- For each i, traverse the remaining elements using index j = i + 1.
- Check if arr[i] + arr[j] is equal to the given target.
- If the sum matches the target, increment count.
- After checking all possible pairs, return count.
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of pairs whose sum is equal to target
int countPairs(vector<int> &arr, int target)
{
int n = arr.size();
int count = 0;
// Generate all possible pairs
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
// Check if the current pair sums to the target
if (arr[i] + arr[j] == target)
count++;
}
}
return count;
}
int main()
{
vector<int> arr = {-1, 1, 5, 5, 7};
int target = 6;
cout << countPairs(arr, target) << endl;
return 0;
}
public class GFG {
// Function to count the number of pairs whose sum is
// equal to target
static int countPairs(int[] arr, int target)
{
int n = arr.length;
int count = 0;
// Generate all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the current pair sums to the
// target
if (arr[i] + arr[j] == target)
count++;
}
}
return count;
}
public static void main(String[] args)
{
int[] arr = { -1, 1, 5, 5, 7 };
int target = 6;
System.out.println(countPairs(arr, target));
}
}
# Function to count the number of pairs whose sum is equal to target
def countPairs(arr, target):
n = len(arr)
count = 0
# Generate all possible pairs
for i in range(n):
for j in range(i + 1, n):
# Check if the current pair sums to the target
if arr[i] + arr[j] == target:
count += 1
return count
# Driver Code
if __name__ == "__main__":
arr = [-1, 1, 5, 5, 7]
target = 6
print(countPairs(arr, target))
using System;
class GFG {
// Function to count the number of pairs whose sum is
// equal to target
static int countPairs(int[] arr, int target)
{
int n = arr.Length;
int count = 0;
// Generate all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the current pair sums to the
// target
if (arr[i] + arr[j] == target)
count++;
}
}
return count;
}
static void Main()
{
int[] arr = { -1, 1, 5, 5, 7 };
int target = 6;
Console.WriteLine(countPairs(arr, target));
}
}
// Function to count the number of pairs whose sum is equal
// to target
function countPairs(arr, target)
{
const n = arr.length;
let count = 0;
// Generate all possible pairs
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Check if the current pair sums to the target
if (arr[i] + arr[j] === target)
count++;
}
}
return count;
}
// Driver code
const arr = [ -1, 1, 5, 5, 7 ];
const target = 6;
console.log(countPairs(arr, target));
Output
3
[Expected Approach] Using Two Pointer Technique - O(n) Time and O(1) Space
Since the array is sorted, the idea is to use two pointer technique. We place one pointer at the beginning and another at the end of the array. Based on the current sum, we move one of the pointers to get closer to the target. Whenever a valid pair is found, we count the occurrences of both elements together to efficiently include all pairs formed by duplicate values.
- Initialize two pointers: left = 0 and right = n - 1.
- While left < right, compare the sum arr[left] + arr[right] with the target.
- If the sum is smaller, increment left; if it is larger, decrement right.
- If the sum equals the target, count the consecutive occurrences of both elements.
- If both elements are the same, add cnt × (cnt - 1) / 2 to the answer; otherwise, add cnt1 × cnt2.
- Continue until the two pointers cross, then return the total count.
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of pairs whose sum is equal to target
int countPairs(vector<int> &arr, int target)
{
int n = arr.size();
int count = 0;
// Initialize two pointers
int left = 0, right = n - 1;
while (left < right)
{
// If the current sum is smaller than the target,
// move the left pointer to increase the sum
if (arr[left] + arr[right] < target)
{
left++;
}
// If the current sum is greater than the target,
// move the right pointer to decrease the sum
else if (arr[left] + arr[right] > target)
{
right--;
}
// If the current sum is equal to the target
else
{
int cnt1 = 0, cnt2 = 0;
int ele1 = arr[left];
int ele2 = arr[right];
// Count the occurrences of the left element
while (left <= right && arr[left] == ele1)
{
left++;
cnt1++;
}
// Count the occurrences of the right element
while (left <= right && arr[right] == ele2)
{
right--;
cnt2++;
}
// If both elements are the same, count the
// number of ways to choose any two of them
if (ele1 == ele2)
{
count += (cnt1 * (cnt1 - 1)) / 2;
}
// Otherwise, every occurrence of the left element
// can pair with every occurrence of the right element
else
{
count += cnt1 * cnt2;
}
}
}
return count;
}
int main()
{
vector<int> arr = {-1, 1, 5, 5, 7};
int target = 6;
cout << countPairs(arr, target) << endl;
return 0;
}
public class GFG {
// Function to count the number of pairs whose sum is
// equal to target
static int countPairs(int[] arr, int target)
{
int n = arr.length;
int count = 0;
// Initialize two pointers
int left = 0, right = n - 1;
while (left < right) {
// If the current sum is smaller than the
// target, move the left pointer to increase the
// sum
if (arr[left] + arr[right] < target) {
left++;
}
// If the current sum is greater than the
// target, move the right pointer to decrease
// the sum
else if (arr[left] + arr[right] > target) {
right--;
}
// If the current sum is equal to the target
else {
int cnt1 = 0, cnt2 = 0;
int ele1 = arr[left];
int ele2 = arr[right];
// Count the occurrences of the left element
while (left <= right && arr[left] == ele1) {
left++;
cnt1++;
}
// Count the occurrences of the right
// element
while (left <= right
&& arr[right] == ele2) {
right--;
cnt2++;
}
// If both elements are the same, count the
// number of ways to choose any two of them
if (ele1 == ele2) {
count += (cnt1 * (cnt1 - 1)) / 2;
}
// Otherwise, every occurrence of the left
// element can pair with every occurrence of
// the right element
else {
count += cnt1 * cnt2;
}
}
}
return count;
}
public static void main(String[] args)
{
int[] arr = { -1, 1, 5, 5, 7 };
int target = 6;
System.out.println(countPairs(arr, target));
}
}
# Function to count the number of pairs whose sum is equal to target
def countPairs(arr, target):
n = len(arr)
count = 0
# Initialize two pointers
left, right = 0, n - 1
while left < right:
# If the current sum is smaller than the target,
# move the left pointer to increase the sum
if arr[left] + arr[right] < target:
left += 1
# If the current sum is greater than the target,
# move the right pointer to decrease the sum
elif arr[left] + arr[right] > target:
right -= 1
# If the current sum is equal to the target
else:
cnt1 = 0
cnt2 = 0
ele1 = arr[left]
ele2 = arr[right]
# Count the occurrences of the left element
while left <= right and arr[left] == ele1:
left += 1
cnt1 += 1
# Count the occurrences of the right element
while left <= right and arr[right] == ele2:
right -= 1
cnt2 += 1
# If both elements are the same, count the
# number of ways to choose any two of them
if ele1 == ele2:
count += (cnt1 * (cnt1 - 1)) // 2
# Otherwise, every occurrence of the left element
# can pair with every occurrence of the right element
else:
count += cnt1 * cnt2
return count
# Driver Code
if __name__ == "__main__":
arr = [-1, 1, 5, 5, 7]
target = 6
print(countPairs(arr, target))
using System;
class GFG {
// Function to count the number of pairs whose sum is
// equal to target
static int countPairs(int[] arr, int target)
{
int n = arr.Length;
int count = 0;
// Initialize two pointers
int left = 0, right = n - 1;
while (left < right) {
// If the current sum is smaller than the
// target, move the left pointer to increase the
// sum
if (arr[left] + arr[right] < target) {
left++;
}
// If the current sum is greater than the
// target, move the right pointer to decrease
// the sum
else if (arr[left] + arr[right] > target) {
right--;
}
// If the current sum is equal to the target
else {
int cnt1 = 0, cnt2 = 0;
int ele1 = arr[left];
int ele2 = arr[right];
// Count the occurrences of the left element
while (left <= right && arr[left] == ele1) {
left++;
cnt1++;
}
// Count the occurrences of the right
// element
while (left <= right
&& arr[right] == ele2) {
right--;
cnt2++;
}
// If both elements are the same, count the
// number of ways to choose any two of them
if (ele1 == ele2) {
count += (cnt1 * (cnt1 - 1)) / 2;
}
// Otherwise, every occurrence of the left
// element can pair with every occurrence of
// the right element
else {
count += cnt1 * cnt2;
}
}
}
return count;
}
static void Main()
{
int[] arr = { -1, 1, 5, 5, 7 };
int target = 6;
Console.WriteLine(countPairs(arr, target));
}
}
// Function to count the number of pairs whose sum is equal
// to target
function countPairs(arr, target)
{
const n = arr.length;
let count = 0;
// Initialize two pointers
let left = 0;
let right = n - 1;
while (left < right) {
// If the current sum is smaller than the target,
// move the left pointer to increase the sum
if (arr[left] + arr[right] < target) {
left++;
}
// If the current sum is greater than the target,
// move the right pointer to decrease the sum
else if (arr[left] + arr[right] > target) {
right--;
}
// If the current sum is equal to the target
else {
let cnt1 = 0;
let cnt2 = 0;
const ele1 = arr[left];
const ele2 = arr[right];
// Count the occurrences of the left element
while (left <= right && arr[left] === ele1) {
left++;
cnt1++;
}
// Count the occurrences of the right element
while (left <= right && arr[right] === ele2) {
right--;
cnt2++;
}
// If both elements are the same, count the
// number of ways to choose any two of them
if (ele1 === ele2) {
count += (cnt1 * (cnt1 - 1)) / 2;
}
// Otherwise, every occurrence of the left
// element can pair with every occurrence of the
// right element
else {
count += cnt1 * cnt2;
}
}
}
return count;
}
// Driver code
const arr = [ -1, 1, 5, 5, 7 ];
const target = 6;
console.log(countPairs(arr, target));
Output
3