882859. Count all triplets with given sum in sorted array
Medium
Here is a detailed Markdown blog post for the problem "Count all triplets with given sum in sorted array":
Count all triplets with given sum in sorted array
Summary
Given an array of integers, count the number of triplets that have a specific sum. The array is already sorted.
This problem involves using the two-pointer algorithm and hash to solve the problem efficiently. The key concept involved is finding pairs of elements that add up to a certain value.
Detailed Explanation
To solve this problem, we will use the two-pointer technique along with a hash set to keep track of the elements we have seen so far.
Here's the step-by-step breakdown:
- Initialize three pointers:
i,jandk. All are initially at the start of the array. - Initialize a variable
countto store the count of triplets that sum up to the target value. - Iterate through the array with pointer
i. - For each element, calculate the target value minus the current element (
target - arr[i]). This will be our target sum for the remaining elements. - Use pointer
jto find the first occurrence of this target sum in the hash set. If we haven't seen this sum before, add it to the hash set and movejto the next element. - Move pointer
kuntil we have found a pair that sums up to the target value minus the current element (arr[j] + arr[k] == target - arr[i]). The number of such pairs is equal to the count of triplets that sum up to the target value. - Increment the
countvariable by the count of triplets and move all three pointers.
Time complexity: O(n^2) Space complexity: O(n)
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class CountTriplets {
public static int countTriplets(int[] arr, int target) {
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
for (int i = 0; i < arr.length; i++) {
int targetSum = target - arr[i];
if (map.containsKey(targetSum)) {
int jIndex = map.get(targetSum);
while (jIndex < i) {
count += jIndex + 1;
jIndex++;
}
} else {
map.put(arr[i], i);
}
}
return count;
}
}