Open In App

2 Sum - Count distinct pairs with given sum

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n and an integer target, the task is to count the number of distinct pairs in the array whose sum is equal to target.

Examples:

Input: arr[] = { 5, 6, 5, 7, 7, 8 }, target = 13 
Output:
Explanation: Distinct pairs with sum equal to 13 are (5, 8) and (6, 7). 

Input: arr[] = { 2, 6, 7, 1, 8, 3 }, target = 10 
Output: 2 
Explanation: Distinct pairs with sum equal to 10 are (2, 8) and (7, 3). 

[Naive Approach] Using Three Nested Loops - O(n^3) Time and O(1) Space

A simple approach is to generate all possible pairs using two nested loops and if they add up to target value, then for each such pair check whether this pair already exists in the result or not.

C++
// C++ program to count all distinct pairs with
// given target using three nested loops

#include <bits/stdc++.h>
using namespace std;

// Function to find all possible pairs with the sum target
int cntDistinctPairs(vector<int> &arr, int target) {
    vector<vector<int>> res;
    int n = arr.size();
	
    // Iterating over all possible pairs
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[i] + arr[j] == target) {
                vector<int> cur = {arr[i], arr[j]};
              	sort(cur.begin(), cur.end());
              
              	// Making sure that all pairs with target
              	// sum are distinct
              	if(find(res.begin(), res.end(), cur) == res.end())
                   res.push_back(cur);
            }
        }
    }

    return res.size();
}

int main() {
    vector<int> arr = { 5, 6, 5, 7, 7, 8 };
  	int target = 13;
  	
    cout << cntDistinctPairs(arr, target);
    return 0;
}
Java
// Java program to count all distinct pairs with
// given target using three nested loops

import java.util.ArrayList;
import java.util.Arrays;

class GfG {
  
    // Function to find all possible pairs with the sum target
    static int cntDistinctPairs(int[] arr, int target) {
        ArrayList<int[]> res = new ArrayList<>();
        int n = arr.length;

        // Iterating over all possible pairs
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] + arr[j] == target) {
                    int[] cur = {arr[i], arr[j]};
                    Arrays.sort(cur);
                  
                    // Making sure that all pairs with 
                  	// target sum are distinct
                    boolean isDistinct = true;
                    for (int[] pair : res) {
                        if (Arrays.equals(pair, cur)) {
                            isDistinct = false;
                            break;
                        }
                    }
                    if (isDistinct) {
                        res.add(cur);
                    }
                }
            }
        }
        return res.size();
    }

    public static void main(String[] args) {
        int[] arr = {5, 6, 5, 7, 7, 8};
        int target = 13;
        
        System.out.println(cntDistinctPairs(arr, target));
    }
}
Python
# Python program to count all distinct pairs with
# given target using three nested loops

def cntDistinctPairs(arr, target):
    res = []
    n = len(arr)

    # Iterating over all possible pairs
    for i in range(n):
        for j in range(i + 1, n):
            if arr[i] + arr[j] == target:
                cur = [arr[i], arr[j]]
                cur.sort()
                
                # Making sure that all pairs with target
                # sum are distinct
                if cur not in res:
                    res.append(cur)

    return len(res)

if __name__ == "__main__":
    arr = [5, 6, 5, 7, 7, 8]
    target = 13
    print(cntDistinctPairs(arr, target))
C#
// C# program to count all distinct pairs with
// given target using three nested loops

using System;
using System.Collections.Generic;

class GfG {
  
    // Function to find all possible pairs with the sum target
    static int cntDistinctPairs(int[] arr, int target) {
        List<List<int>> res = new List<List<int>>();
        int n = arr.Length;

        // Iterating over all possible pairs
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] + arr[j] == target) {
                    List<int> cur = new List<int> { arr[i], arr[j] };
                    cur.Sort();
                  
                    // Making sure that all pairs with target
                    // sum are distinct
                    if (!res.Exists(pair => pair[0] == cur[0] && pair[1] == cur[1])) {
                        res.Add(cur);
                    }
                }
            }
        }

        return res.Count;
    }

    static void Main() {
        int[] arr = { 5, 6, 5, 7, 7, 8 };
        int target = 13;
        
        Console.WriteLine(cntDistinctPairs(arr, target));
    }
}
JavaScript
// JavaScript program to count all distinct pairs with
// given target using three nested loops

function cntDistinctPairs(arr, target) {
    let res = [];
    let n = arr.length;

    // Iterating over all possible pairs
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if (arr[i] + arr[j] === target) {
                let cur = [arr[i], arr[j]];
                cur.sort((a, b) => a - b);
                
                // Making sure that all pairs with target
                // sum are distinct
                if (!res.some(pair => pair[0] === cur[0] && pair[1] === cur[1])) {
                    res.push(cur);
                }
            }
        }
    }

    return res.length;
}

const arr = [5, 6, 5, 7, 7, 8];
const target = 13;

console.log(cntDistinctPairs(arr, target));

Output
2

Time Complexity: O(n^3), where n is size of arr[].
Auxiliary Space: O(n^2), as in the worst case we can have (n * (n - 1))/2 pairs in the result.

[Better Approach] Sorting and Two Pointer technique - O(n*log n) Time and O(1) Space

The idea is to sort the array and use two pointers at the beginning and end of the array. If the sum of the elements at these pointers equals target, we update the pair counter and skip duplicates to ensure they are distinct. If the sum is less than the target, we move the left pointer towards right and if sum is greater than target, we move the right pointer towards left. This continues until all pairs are checked, giving us the total count of distinct pairs.

C++
// C++ program to count all distinct pairs with given
// target using sorting and two pointer technique

#include <bits/stdc++.h>
using namespace std;

// Function to count distinct pairs whose sum is  
// equal to target
int cntDistinctPairs(vector<int> &arr, int target) {
    int res = 0;
  	int n = arr.size();
    sort(arr.begin(), arr.end());

    int left = 0, right = n - 1;

    while (left < right) {
        if (arr[left] + arr[right] == target) {
            res++;
            
            // Skip consecutive duplicate array elements
            while (left < right && arr[left] == arr[left + 1])
                left++;

            // Skip consecutive duplicate array elements
            while (left < right && arr[right] == arr[right - 1])
                right--;

            left++;
            right--;
        }
        else if (arr[left] + arr[right] < target)
            left++;
        else
            right--;
    }
    return res;
}

int main() {
    vector<int> arr = { 5, 6, 5, 7, 7, 8 };
    int target = 13;
  	
    cout << cntDistinctPairs(arr, target);
    return 0;
}
C
// C program to count all distinct pairs with given
// target using sorting and two pointer technique

#include <stdio.h>

// Function to compare two integers (used for sorting)
int compare(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

// Function to count distinct pairs whose sum is  
// equal to target
int cntDistinctPairs(int arr[], int n, int target) {
    int res = 0;
    qsort(arr, n, sizeof(int), compare);

    int left = 0, right = n - 1;

    while (left < right) {
        if (arr[left] + arr[right] == target) {
            res++;
            
            // Skip consecutive duplicate array elements
            while (left < right && arr[left] == arr[left + 1])
                left++;

            // Skip consecutive duplicate array elements
            while (left < right && arr[right] == arr[right - 1])
                right--;

            left++;
            right--;
        }
        else if (arr[left] + arr[right] < target)
            left++;
        else
            right--;
    }
    return res;
}

int main() {
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int target = 13;
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("%d\n", cntDistinctPairs(arr, n, target));
    return 0;
}
Java
// Java program to count all distinct pairs with given
// target using sorting and two pointer technique

import java.util.Arrays;

class GfG {

    // Function to count distinct pairs whose sum is  
    // equal to target
    static int cntDistinctPairs(int[] arr, int target) {
        int res = 0;
        int n = arr.length;
        Arrays.sort(arr);

        int left = 0, right = n - 1;

        while (left < right) {
            if (arr[left] + arr[right] == target) {
                res++;
                
                // Skip consecutive duplicate array elements
                while (left < right && arr[left] == arr[left + 1])
                    left++;

                // Skip consecutive duplicate array elements
                while (left < right && arr[right] == arr[right - 1])
                    right--;

                left++;
                right--;
            } 
            else if (arr[left] + arr[right] < target)
                left++;
            else
                right--;
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = { 5, 6, 5, 7, 7, 8 };
        int target = 13;

        System.out.println(cntDistinctPairs(arr, target));
    }
}
Python
# Python program to count all distinct pairs with given
# target using sorting and two pointer technique

def cntDistinctPairs(arr, target):
    res = 0
    n = len(arr)
    arr.sort()

    left = 0
    right = n - 1

    while left < right:
        if arr[left] + arr[right] == target:
            res += 1
            
            # Skip consecutive duplicate array elements
            while left < right and arr[left] == arr[left + 1]:
                left += 1

            # Skip consecutive duplicate array elements
            while left < right and arr[right] == arr[right - 1]:
                right -= 1
            left += 1
            right -= 1
        elif arr[left] + arr[right] < target:
            left += 1
        else:
            right -= 1
    return res

if __name__ == "__main__":
    arr = [5, 6, 5, 7, 7, 8]
    target = 13
    
    print(cntDistinctPairs(arr, target))
C#
// C# program to count all distinct pairs with given
// target using sorting and two pointer technique

using System;
using System.Collections.Generic;

class GfG {
    
    // Function to count distinct pairs whose sum is  
    // equal to target
    static int cntDistinctPairs(int[] arr, int target) {
        int res = 0;
        int n = arr.Length;
        Array.Sort(arr);

        int left = 0, right = n - 1;

        while (left < right) {
            if (arr[left] + arr[right] == target) {
                res++;

                // Skip consecutive duplicate array elements
                while (left < right && arr[left] == arr[left + 1])
                    left++;

                // Skip consecutive duplicate array elements
                while (left < right && arr[right] == arr[right - 1])
                    right--;

                left++;
                right--;
            }
            else if (arr[left] + arr[right] < target)
                left++;
            else
                right--;
        }
        return res;
    }

    static void Main() {
        int[] arr = { 5, 6, 5, 7, 7, 8 };
        int target = 13;

        Console.WriteLine(cntDistinctPairs(arr, target));
    }
}
JavaScript
// JavaScript program to count all distinct pairs with given
// target using sorting and two pointer technique

function cntDistinctPairs(arr, target) {
    let res = 0;
    let n = arr.length;
    arr.sort((a, b) => a - b);

    let left = 0, right = n - 1;

    while (left < right) {
        if (arr[left] + arr[right] === target) {
            res++;
            
            // Skip consecutive duplicate array elements
            while (left < right && arr[left] === arr[left + 1])
                left++;

            // Skip consecutive duplicate array elements
            while (left < right && arr[right] === arr[right - 1])
                right--;

            left++;
            right--;
        } 
        else if (arr[left] + arr[right] < target)
            left++;
        else
            right--;
    }
    return res;
}

const arr = [5, 6, 5, 7, 7, 8];
const target = 13;

console.log(cntDistinctPairs(arr, target));

Output
2

Time Complexity: O(n * log(n)), where n is size of arr[]
Auxiliary Space: O(1)

[Expected Approach] Using Hash Map - O(n) Time and O(n) Space

The idea is to maintain a hash map to track how many times each element has occurred in the array so far. Traverse all the elements and for each element arr[i], check if the complement (target - arr[i]) already exists in the map, if it exists then we have found a pair whose sum is equal to target.

How to ensure that we don't include duplicate pairs?

To ensure that we don't include duplicate pairs, we can have two cases:

  • If arr[i] == complement, then we check for exactly one occurrence of arr[i] before index i. If it occurs exactly once, then arr[i] can pair with itself and form a pair with sum = target. Also, if there is more than one occurrence of arr[i], then it means that the pair has already been counted previously, so this element forms a duplicate pair.
  • If arr[i] != complement, then we check for at least one occurrence of complement and no occurrence of arr[i] before index i. If both the conditions are satisfied, then it means that arr[i] and complement forms a unique pair with sum = target.
C++
// C++ program to count all distinct pairs with given
// sum using Hash Map

#include <bits/stdc++.h>
using namespace std;

int cntDistinctPairs(vector<int> &arr, int target) {
    int res = 0;
  	int n = arr.size();
  	
    // frequency map to store the frequency of all elements
    unordered_map<int, int> freq;

    for (int i = 0; i < n; i++) {

        int complement = target - arr[i];
      
        // If the complement is equal to arr[i], then there should
        // be only one occurrence of complement in the hash map
        if (complement == arr[i]) {
            if (freq[complement] == 1) 
                res++;
        }
      
      	// if complement is not equal to arr[i], then there should
        // be at least one occurrence of complement and no occurrence
        // of current element in the hash map
      	else if (freq[complement] > 0 && freq[arr[i]] == 0) {
            res++;
        }
      
        // Add the current element in the hash map
        freq[arr[i]]++;
    }
  
  	return res;
}

int main() {
    vector<int> arr = {5, 6, 5, 7, 7, 8};
    int target = 13;
  
    cout << cntDistinctPairs(arr, target);
    return 0;
}
Java
// Java program to count all distinct pairs with given
// sum using Hash Map

import java.util.HashMap;
import java.util.Map;

class GfG {
    static int cntDistinctPairs(int[] arr, int target) {
        int res = 0;
        int n = arr.length;

        // frequency map to store the frequency of all elements
        Map<Integer, Integer> freq = new HashMap<>();

        for (int i = 0; i < n; i++) {
            int complement = target - arr[i];

            // If the complement is equal to arr[i], then there should
            // be only one occurrence of complement in the hash map
            if (complement == arr[i]) {
                if (freq.getOrDefault(complement, 0) == 1) 
                    res++;
            }
          
            // if complement is not equal to arr[i], then there should
            // be at least one occurrence of complement and no occurrence
            // of current element in the hash map
            else if (freq.getOrDefault(complement, 0) > 0 &&
                     				freq.getOrDefault(arr[i], 0) == 0) {
                res++;
            }
          
            // Add the current element in the hash map
            freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
        }
      
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {5, 6, 5, 7, 7, 8};
        int target = 13;
      
        System.out.println(cntDistinctPairs(arr, target));
    }
}
Python
# Python program to count all distinct pairs with given
# sum using Hash Map

def cntDistinctPairs(arr, target):
    res = 0
    n = len(arr)
    
    # frequency map to store the frequency of all elements
    freq = {}

    for i in range(n):
        complement = target - arr[i]
      
        # If the complement is equal to arr[i], then there should
        # be only one occurrence of complement in the hash map
        if complement == arr[i]:
            if freq.get(complement, 0) == 1:
                res += 1
      
        # if complement is not equal to arr[i], then there should
        # be at least one occurrence of complement and no occurrence
        # of current element in the hash map
        elif freq.get(complement, 0) > 0 and freq.get(arr[i], 0) == 0:
            res += 1
      
        # Add the current element in the hash map
        freq[arr[i]] = freq.get(arr[i], 0) + 1
  
    return res

if __name__ == "__main__":
    arr = [5, 6, 5, 7, 7, 8]
    target = 13
  
    print(cntDistinctPairs(arr, target))
C#
// C# program to count all distinct pairs with given
// sum using Hash Map

using System;
using System.Collections.Generic;

class GfG {
    static int cntDistinctPairs(List<int> arr, int target) {
        int res = 0;
        int n = arr.Count;

        // frequency map to store the frequency of all elements
        Dictionary<int, int> freq = new Dictionary<int, int>();

        for (int i = 0; i < n; i++) {
            int complement = target - arr[i];

            // If the complement is equal to arr[i], then there should
            // be only one occurrence of complement in the hash map
            if (complement == arr[i]) {
                if (freq.GetValueOrDefault(complement, 0) == 1)
                    res++;
            }

            // if complement is not equal to arr[i], then there should
            // be at least one occurrence of complement and no occurrence
            // of current element in the hash map
            else if (freq.GetValueOrDefault(complement, 0) > 0 
                             && freq.GetValueOrDefault(arr[i], 0) == 0) {
                res++;
            }

            // Add the current element in the hash map
            if (freq.ContainsKey(arr[i]))
                freq[arr[i]]++;
            else
                freq[arr[i]] = 1;
        }

        return res;
    }

    static void Main(string[] args) {
        List<int> arr = new List<int> { 5, 6, 5, 7, 7, 8 };
        int target = 13;

        Console.WriteLine(cntDistinctPairs(arr, target));
    }
}
JavaScript
// JavaScript program to count all distinct pairs with given
// sum using Hash Map

function cntDistinctPairs(arr, target) {
    const st = new Set();
    const seen = new Set();
    let res = 0;

    for (let i = 0; i < arr.length; i++) {
        const complement = target - arr[i];

        // If complement of current element exist in set 
        // and is not previously seen then count this pair
        if (st.has(complement) && !seen.has(arr[i])) {
            res++;
            seen.add(arr[i]);
            seen.add(complement);
        }
        
        // Add the current element in the hash map
        st.add(arr[i]);
    }
    return res;
}

const arr = [5, 6, 5, 7, 7, 8];
const target = 13;

console.log(cntDistinctPairs(arr, target));

Output
2

Time Complexity: O(n), where n is size of arr[]
Auxiliary Space: O(n)


Similar Reads