Sunday, 2 August 2015

Find pairs of numbers where sum equal to x

Given an array. Find pairs of numbers that add up to a given value 'x'.

This problem can be solved in following way.
a.   First sort the numbers.
b.   Scan the array using two pointers one from beginning and other from end of the array.
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class SumCheck {

 public static Map<Integer, Integer> getPairs(int arr[], int matchSum) {
  Map<Integer, Integer> map = new LinkedHashMap<>();

  Objects.nonNull(arr);
  if (arr.length < 2)
   return map;

  Arrays.sort(arr);
  int leftCounter = 0, rightCounter = arr.length - 1;

  while (leftCounter <= rightCounter) {
   int sum = arr[leftCounter] + arr[rightCounter];

   if (sum == matchSum)
    map.put(arr[leftCounter], arr[rightCounter]);

   if (matchSum > sum) {
    leftCounter++;
    continue;
   }
   rightCounter--;
  }

  return map;
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertTrue;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class SumCheckTest {

 @Test
 public void test1() {
  int arr1[] = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 };
  int arr2[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

  Map<Integer, Integer> actualMap1 = SumCheck.getPairs(arr1, 18);
  Map<Integer, Integer> actualMap2 = SumCheck.getPairs(arr2, 11);

  Map<Integer, Integer> expectedMap1 = new HashMap<>();
  Map<Integer, Integer> expectedMap2 = new HashMap<>();

  expectedMap1.put(0, 18);
  expectedMap1.put(2, 16);
  expectedMap1.put(4, 14);
  expectedMap1.put(6, 12);
  expectedMap1.put(8, 10);

  expectedMap2.put(2, 9);
  expectedMap2.put(3, 8);
  expectedMap2.put(4, 7);
  expectedMap2.put(5, 6);

  assertTrue(actualMap1.equals(expectedMap1));
  assertTrue(actualMap2.equals(expectedMap2));

 }
}



No comments:

Post a Comment