Amazon Interview Question
Software Engineer / Developers1.sort
2.get the sum of the distinct numbers sum2.
3.get the sum of all the numbers sum3.
4. the result is mod (sum3,sum2)
If you sort the numbers then the other steps are unnecessary. Just have a pass over them and count the number of occurrences. If it happens to be odd.. thats it :-)
How about doing the first steps of the count sort? Use an array to keep the count of the numbers. Array size can be (max of the numbers - minimum of the numbers) and update the count of the number at the appropriate index. Wherever the count is odd, that will be the number. You don't even need to sort the array
I am not sure, if it is optimam solution. It goes as.
Step 1 : Make an array of unique number(Say tempArray) from given array (Say OriArray)
Step 2 : Get Sum1 = 2n * sum of all numbers in tempArray
Setp 3 : Get Sum2 = sum of all numbers in OriArray
Setp 4 : get diffNum = Sum2 - Sum1
Setp 5 : DiffNum is the one which has occurances 2n+1 times in OriArray.
@Ravi
Your solution works and seems reasonably efficient. My only qualm is how would you make an unique array of elements (step 1). You have to check all the elements in your temp array for every element of the original array. Then I guess it would be n^2.
An alternative approach if the range of the numbers is known is to use a bit vector of the size of that range. On seeing a number, we would increment that corresponding bit in the vector.
Finally we would do one more iteration to find out the extra number.
1) go through the array once, find out the occurrence O of array[0]
Also while traverse, calculate the sum of the array S, multiplication of the array M.
if O % 2 == 1
return arra[0] (you are lucky)
2) else
solve this equation:
X*(2*O) + Y*(2*O+1) = S
X^(2*O) * Y^(2*O+1) = M
(Y is the number witch appear (2N+1) times
package com;
import java.util.HashSet;
import java.util.Set;
public class General {
static char findx(char[] arr,int length){
HashSet s=new HashSet();
for (int i = 0; i < arr.length; i++) {
if(s.add(arr[i]) == false)
s.remove(arr[i]);
}
return (Character)s.iterator().next();
}
public static void main(String[] args) {
char[] arr={'a','b','c','d','a','b','c','d','e','a'};
System.out.println(findx(arr,10));
}
}
package com;
import java.util.HashSet;
import java.util.Set;
public class General {
static char findx(char[] arr,int length){
HashSet s=new HashSet();
for (int i = 0; i < arr.length; i++) {
if(s.add(arr[i]) == false)
s.remove(arr[i]);
}
return (Character)s.iterator().next();
}
public static void main(String[] args) {
char[] arr={'a','b','c','d','a','b','c','d','e','a'};
System.out.println(findx(arr,10));
}
}
whats the Q and how is it related to median ? as anon says.
- funny July 28, 2008