702779. Count pair sum
Basic
Count Pair Sum
Summary
The "Count pair sum" problem involves counting the number of pairs in an array that have a specific sum. This problem can be solved using various algorithms, including hash-based and sorting-based approaches.
Detailed Explanation
Given an array arr of size n, our goal is to find the number of pairs (i, j) such that arr[i] + arr[j] = targetSum. We will use a hash-based approach to solve this problem efficiently.
Here's a step-by-step breakdown of the solution:
- Initialize an empty hashmap
sumCountto store the count of each sum in the array. - Iterate through the array and calculate the sum of each pair
(i, j)for all possible values ofj. For each sum, increment the corresponding count insumCount. - Initialize a variable
countto 0, which will store the total number of pairs that have the target sum. - Iterate through the array again and check if the current element's index plus the count of the remaining elements in the array is equal to
targetSum. If it is, incrementcountby the count of the remaining elements. - Return the final value of
count, which represents the number of pairs that have the target sum.
Time complexity: O(n) Space complexity: O(n)
Here's an ASCII art diagram illustrating the steps:
arr = [1, 2, 3, 4, 5]
// Initialize hashmap
sumCount = {}
// Iterate through array and calculate sums
for i in range(len(arr)):
for j in range(i+1, len(arr)):
sum = arr[i] + arr[j]
if sum not in sumCount:
sumCount[sum] = 0
sumCount[sum] += 1
// Count pairs with target sum
count = 0
for i in range(len(arr)):
remainingSum = targetSum - arr[i]
if remainingSum in sumCount:
count += sumCount[remainingSum]
return count
Optimized Solutions
Java
public int countPairs(int[] arr, int targetSum) {
Map<Integer, Integer> sumCount = new HashMap<>();
for (int i : arr) {
for (int j = i + 1; j < arr.length; j++) {
int sum = i + j;
sumCount.put(sum, sumCount.getOrDefault(sum, 0) + 1);
}
}
int count = 0;
for (int i : arr) {
int remainingSum = targetSum - i;
if (sumCount.containsKey(remainingSum)) {
count += sumCount.get(remainingSum);
}
}
return count;
}