VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-distinct-pairs-with-given-sum/

⇱ 2 Sum - Count distinct pairs with given sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

2 Sum - Count distinct pairs with given sum

Last Updated : 23 Jul, 2025

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.


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.


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.

Output
2

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

Comment