Tuesday 24 May 2016

Find the missing element

Find the missing element from the given 2 arrays, second array is duplicate.
array 1: [1,2,3,4,5,6,7]
array2: [1,3,4,5,6,7]


Answer is 2.

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class ArrayUtil {
 private static void checkPreConditions(int arr1[], int arr2[]) {
  if (Objects.isNull(arr1) || Objects.isNull(arr2)) {
   throw new NullPointerException("Arrays Shouldn't be null");
  }

  if (arr1.length != arr2.length + 1) {
   throw new IllegalArgumentException("Illegal Arguments");
  }
 }

 public static int approach1(int arr1[], int arr2[]) {
  checkPreConditions(arr1, arr2);

  int data = arr1[0];

  for (int i = 1; i < arr1.length; i++) {
   data ^= arr1[i];
   data ^= arr2[i - 1];
  }

  return data;
 }

 public static int approach2(int arr1[], int arr2[]) {
  checkPreConditions(arr1, arr2);

  int sum1 = arr1[0], sum2 = 0;

  for (int i = 1; i < arr1.length; i++) {
   sum1 = sum1 + arr1[i];
   sum2 = sum2 + arr2[i - 1];
  }

  return sum1 - sum2;
 }

 public static int approach3(int arr1[], int arr2[]) {

  checkPreConditions(arr1, arr2);

  Set<Integer> hashSet = new HashSet<>();

  for (int i : arr1) {
   hashSet.add(i);
  }

  for (int i : arr2) {
   if (hashSet.contains(i))
    hashSet.remove(i);
  }

  for (int missed : hashSet)
   return missed;

  return -1;
 }
}


import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ArrayUtilTest {

 @Test
 public void test() {
  int arr1[] = { 1, 2, 3, 4, 5, 6, 7 };
  int arr2[] = { 1, 3, 4, 5, 6, 7 };

  assertEquals(ArrayUtil.approach1(arr1, arr2), 2);
  assertEquals(ArrayUtil.approach2(arr1, arr2), 2);
  assertEquals(ArrayUtil.approach3(arr1, arr2), 2);
 }
}



No comments:

Post a Comment