![]() |
VOOZH | about |
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: 2
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).
Table of Content
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.
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.
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.
2
Time Complexity: O(n * log(n)), where n is size of arr[]
Auxiliary Space: O(1)
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:
2
Time Complexity: O(n), where n is size of arr[]
Auxiliary Space: O(n)