![]() |
VOOZH | about |
Given an array of N positive integers. Count the number of pairs whose sum exists in the given array. While repeating pairs will not be counted again. And we can't make a pair using same position element. Eg : (2, 1) and (1, 2) will be considered as only one pair. Please read all examples carefully.
Examples:
Input : arr[] = {1, 2, 3, 5, 10}
Output : 2
Explanation : Here there are two such pairs:
(1 + 2) = 3, (2 + 3) = 5.
Note : Here we can't take pair (5, 5) as
we can see 5 is not coming twice
Input : arr[] = {1, 5, 6, 4, -1, 5}
Output : 4
Explanation : (1 + 5) = 6, (1 + 4) = 5,
(5 + -1) = 4, (6 + -1) = 5
Note : Here (1, 5) comes twice will be
considered as only one pair.
Input : arr[] = {5, 5, 5, 5, 10}
Output : 1
Explanation : (5 + 5) = 10
Note : Here (5, 5) comes twice will be
considered as only one pair.
The idea is to map of pairs to find unique elements. We first store elements and their counts in a map. Then we traverse array elements, for every pair of elements (arr[i], arr[j]), we check if (arr[i] + arr[j]) exists in array. If exists, then we check if it is already counted using map of pairs. If not already counted, then we increment count.
Implementation:
6
Time complexity: O(n^2)
Space complexity: O(n)