1. Introduction
This blog post addresses the Three Number Sum (3Sum) problem, a more complex variant of the Two Number Sum problem. The goal is to find all triplets in an array that sum up to a given target value.
Problem
Given an array of integers, find all triplets in the array that sum up to a given target value. In other words, for an array arr and a target value target, return all triplets a, b, c such that a + b + c = target.
Example:
Input array: [7, 12, 3, 1, 2, -6, 5, -8, 6]
Target sum: 0
Output: [[2, -8, 6], [3, 5, -8], [1, -6, 5]]
2. Solution Steps
1. Sort the array.
2. Use three-pointers to find triplets: one for the current element and two for finding a pair that sums up the complement of the current element.
3. For each element in the array, use a pair of pointers to scan the remaining part of the array to find pairs that sum up to the required value.
4. Move the pointers appropriately to avoid duplicates and find all the unique triplets.
5. Add each valid triplet to the result list.
6. Return the list of triplets.
3. Code Program
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
// Main method for testing
public static void main(String[] args) {
int[] input = {7, 12, 3, 1, 2, -6, 5, -8, 6};
int targetSum = 0;
List<int[]> triplets = threeNumberSum(input, targetSum);
for (int[] triplet : triplets) {
System.out.println(Arrays.toString(triplet));
}
}
// Method to find all triplets with the given sum
public static List<int[]> threeNumberSum(int[] arr, int targetSum) {
Arrays.sort(arr);
List<int[]> triplets = new ArrayList<>();
for (int i = 0; i < arr.length - 2; i++) {
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
int currentSum = arr[i] + arr[left] + arr[right];
if (currentSum == targetSum) {
triplets.add(new int[]{arr[i], arr[left], arr[right]});
left++;
right--;
} else if (currentSum < targetSum) {
left++;
} else if (currentSum > targetSum) {
right--;
}
}
}
return triplets;
}
}
Output:
[2, -8, 6] [3, 5, -8] [1, -6, 5]
Explanation:
For the input array [7, 12, 3, 1, 2, -6, 5, -8, 6] and target sum 0, the threeNumberSum method finds all the unique triplets whose sum is 0. It first sorts the array and then iterates through it, using two pointers to find pairs that, together with the current element, sum up to 0. The output triplets are [2, -8, 6], [3, 5, -8], and [1, -6, 5].
Comments
Post a Comment
Leave Comment