In this artcile, we will learn to resolve the 3Sum problem by using two pointers algorithm

## Problem

• Given an array of integers `A[N]` and an integer number `targetSum`

• Find if existing in `A` three integers `A[i]`, `A[j]` and `A[k]` such that `A[i] + A[j] + A[k] = targetSum`

## Example

• Input: `A = {4, -9, 0, 11, 6, -20, 1, 7}`, `targetSum = 10`

• Expected output: `true`

• Explanation: 4 + 0 + 6 = 10

## Two pointers approach

• Sort the given array A

• Traverse through A from i = 0 to i = A.length - 2.

• For each index i, use two indices j and k with j = i + 1 and k = A.length - 1 to walk inward the array

• Do the following while j < k

• Calculate sum of A[i], A[j], and A[k]

• Return true if sum equals to targetSum. Otherwise increase j by 1 if sum < targetSum, or decrease k by 1 if sum > targetSum

• Return false after exit 2 loops

``````import java.util.Arrays;

public class TwoPointers_3Sum {
boolean contains3(int[] a, int targetSum) {
Arrays.sort(a);

for (int i = 0; i < a.length - 2; i++) {
int j = i + 1;
int k = a.length - 1;

while (j < k) {
int sum = a[i] + a[j] + a[k];

if (sum == targetSum) {
return true;
} else if (sum < targetSum) {
j++;
} else {
k--;
}
}
}

return false;
}

public static void main(String[] args) {
int[] a = {4, -9, 0, 11, 6, -20, 1, 7};
System.out.println(new TwoPointers_3Sum().contains3(a, 10));
}
}
``````

Output

``````true
``````

Complexity

• Time complexity: O(n2)

• Space complexity: O(1)