876221. All Pairs With Given Sum
Here is the Markdown blog post for the "All Pairs With Given Sum" problem:
All Pairs With Given Sum
Summary
Find all pairs in a given array that sum up to a target value. This problem involves arrays and hash techniques, making it an easy yet interesting challenge.
Detailed Explanation
To solve this problem, we can use a simple approach involving two pointers technique. The idea is to iterate through the array with two pointers, one starting from the beginning of the array (let's call it i) and the other starting from the end of the array (j). At each step, calculate the sum of the elements at indices i and j. If the sum equals the target value, add the pair (array[i], array[j]) to our result set. Move the pointers accordingly based on whether the sum is less than, greater than, or equal to the target.
Here's a step-by-step breakdown of the solution:
- Initialize an empty list
resultto store the pairs that sum up to the target value. - Iterate through the array with two pointers,
istarting from 0 andjstarting from the end of the array (size - 1). - Calculate the sum of elements at indices
iandj. - If the sum equals the target value, add the pair
(array[i], array[j])to theresultlist. - Move the pointers accordingly:
- If the sum is less than the target, increment
ito increase the sum. - If the sum is greater than the target, decrement
jto decrease the sum.
- If the sum is less than the target, increment
- Repeat steps 2-5 until
iandjmeet in the middle (wheni == j). - Return the
resultlist containing all pairs that sum up to the target value.
Time complexity: O(n), where n is the size of the array, since we only iterate through the array once. Space complexity: O(n), as we store the result in a list of length proportional to the size of the array.
Optimized Solutions
Java
import java.util.*;
public class Main {
public static List<int[]> findPairs(int[] arr, int target) {
List<int[]> result = new ArrayList<>();
int i = 0;
int j = arr.length - 1;
while (i < j) {
int sum = arr[i] + arr[j];
if (sum == target) {
result.add(new int[]{arr[i], arr[j]});
i++;
j--;
} else if (sum < target) {
i++;
} else {
j--;
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int target = 7;
List<int[]> result = findPairs(arr, target);
System.out.println(result); // Output: [[1, 6], [2, 5]]
}
}