Microsoft Interview Question
Software Engineer / Developersinteger pairs?? does that mean 2 numbers at a time..?? 2 consecutive numbers or just any 2 numbers in the whole array?
We can use "Counting sort" here (runs in O(n)), because the range is known (range = sum). But the range should be reasonably small.
int [] hashArr = {1,3,7,12,2,71,8,9,10,6,4};
int numEle = hashArr.length;
Hashtable ht = new Hashtable();
// Add all the elements to the Hash Table
for(int i=0;i<numEle;i++)
ht.put(i, hashArr[i]);
// Check the difference, sum - i = ex whether in HashTable
int sum = 10;
int diff = 0;
for(int j=0;j<numEle;j++){
diff = sum-hashArr[j];
if(ht.contains(diff))
System.out.println(hashArr[j]+":"+diff);
}
What if the sum is 50.. and the array contents are {25,45,30}... ? First it selects 25 and again searching in hash returns 25.. a pair(25,25) that does not exist..
thats a valid point ... hash method fails for this case ... what we can do is also check if (m-new element)== m or not ... if array doesnt contain duplicates .. such cases should be considered invalid
see the introduction to algorithms by carman book O(nlogn) is complexcity...
- DinakaranGct December 31, 2009