educative.io

About the Pattern: Two Pointers - Pair with Target Sum (easy) category


#1

Have questions about Pair with Target Sum (easy)? Go for it!

View the lesson here.


#2

To find out multiple pairs with target Sum:

public class Solution {
public static List<List> targetsum(int [] arr,int k) {
List<List> pair = new LinkedList<List>();

	int first =0;
	int last = arr.length-1;
	int targetDiff;
		while (first<last) {
			targetDiff=k-arr[first];
			if(targetDiff==arr[last]) {
				pair.add(Arrays.asList(first,last));
				last--;
				
			}
			else if(targetDiff<arr[last]) {
				last--;
				}
			if (targetDiff>arr[last]) {
				first++;
				}
		}
	
	return pair;
	
}