Amazon Interview Question
Software Engineer / Developerspublic class hello {
public static void main(String args[]){
int [] arr = {2,4,5,1,7,9,6,8,10,3,12,13, 11, 15}; // 1to15, 14 missing
findmissing(arr);
}
private static void findmissing(int[] arr)
{
int []temp = new int [arr.length+2];
for(int data : arr)
{
temp[data]= 1;
}
for(int i = 1; i < temp.length; i++)
{
if (temp[i]==0)
{
System.out.println(i);
}
}
}
}
I don't like using a temp array, I was in a hurry to solve, further optimizations can be done.
Thanks
Sum all number in the array and subtract from (N*(N+1))/2 if 'N-1' is the size of the array.
The most efficient algorithm to find the missing number in the array is to use the concept of xor we will xor all the array elements and store them in one variable and we will xor all the numbers from 1 to n and store them in one variable and then next we will xor both of them which will return our missing element.
Use XOR
- jj February 19, 2013public class Missing_and_Duplicate {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] intArray2={2,4,7,5,3,1}; // 6 is missing
find_missing(intArray2);
}
public static void find_missing(int[] intArray)
{
int answer = intArray[0];
for(int i=1;i<intArray.length;i++)
{
answer = answer ^ intArray[i];
}
System.out.println("answer="+answer);
}
}