15 August 2010

Puzzle - Find the Unique Number

There are two arrays - a and b. One of the arrays contains one element more than the other. The extra element is unique and all other elements are same but in different order. Find the element that is unique.

For example
a -> {10,2,3,4,6,5,8,7,9,1}
b -> a -> {1,2,3,4,5,6,7,8,9}
Unique element is {10}

Answer

public static int getUniqueKey(int[] bigger, int[] smaller) {    
    
    if(bigger == null || smaller == null || Math.abs(bigger.length - smaller.length!= 1) {
      throw new ArithmeticException("arguments passed is null.");
    }        
    
    // Till now, bigger is not necessarily bigger. let us make it bigger
    
    if(bigger.length < smaller.length) {
      int[] temp = smaller;
      smaller = bigger;
      bigger = temp;          
    }
    
    int biggerValue = 0;
    int smallerValue = 0;
    
    for(int i = 0; i < smaller.length; ++i) {
      biggerValue += bigger[i];
      smallerValue += smaller[i];
    }      
    biggerValue += bigger[bigger.length - 1];
    
    return biggerValue - smallerValue;
  }


Let us discuss one more puzzle in upcoming days in this week.