Google Interview Question
Software Engineer in Testshunt's answer seems to on the correct lines.
interviewer added later that no dupes should be printed.
also asked me to list the (unit) testcases for the function.
Hunt's approach seems correct. As far as Duplicate elimination goes, a slight modification to hunts algorithm to store the intersected element before printing and on the next match, check if the previously stored element is not the same as the current matching element detected. Any opinions ?
@amit, you're correct. :) that'll work....but how about this...
int intersect(int a[],int uba,int b[],int ubb,int c[]) //c is atleast uba+ubb...returns ubc
{
int lba = 0, lbb = 0, lbc = 0;
while( (lba < uba) && (lbb < ubb))
{
if( a[lba] == b[lbb])
{
int t = a[lba];
while(a[lba] == t) lba++;
while(b[lbb] == t) lbb++;
c[lbc++] = t;
}else
if( a[lba] < b[lbb])
lba++;
else
lbb++;
}
return lbc;
}
For solving the above algorithm we will need to do a merge sort operation, and we will compare the elements of the two arrays if the first element of the first array is less than the first element of the second array then increment the index of the first array because there may the next element which intersects with the first array and similarly increment the index of the second array when the element of the second array is less than the first array and when both the array elements are equal then print the element and increment both the array indexes.
- sunny July 31, 2017