Microsoft Interview Question
Software Engineer in Tests<pre lang="" line="1" title="CodeMonkey63451" class="run-this">/* The class name doesn't have to be Main, as long as the class is not public. */
class check {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//int[] arr = new int[5];
int arr[]={1,2,4,6,7,8,10,100,600,1000};
int arr1[]={1,2,3,4,5,6,8,9,10,100,200,300,400,700,1000};
int i=0,j=0,k=0;
while(i < arr.length)
{
for(;j < arr1.length;)
{
if(arr[i] == arr1[j])
{
System.out.println(arr[i]);
i++; j++;
break;
}
else if(arr[i] < arr1[j])
{
i++;
}
else if(arr[i] > arr1[j])
{
j++;
break;
}
}
}
}
}</pre><pre title="CodeMonkey63451" input="yes">
</pre>
let the two arrays be array1[]
array2[]
for(i=0; j=0; i< array1.length(); j<array2.length();) {
if(array1[i]== array2[j]) {
print("found the element %d", array1[i]);
} else if (array1[i] < array2[j]) i++;
else j++;
}
if extra space is given to us we can do it in o(n lgn)
but if not we have to do it inthe 0(nm) solution :)
step 1.
first ort these 2 given sets in the 0(nlgn) time.
after sorting it should be like:)
void printintersectelement(int a[],in b[],int n,int m)
{
int i=0,j=0;
while(i<=n-1)
{
for(;j<m-1;)
{
if(a[i]==b[j])
{
printf("%d",a[i]);
i++;
j++;
break;
}
else if(a[i]<b[j])
{
i++;
break;
}
j++;
}
}
}
For Intersection of 2 arrays,
1. Maintain 2 BitSets one for each array. Size of this bitset wud be the value of largest number present in each array. Size= O(1) Time=O(1)
2. XOR the 2 bitsets . Final result wud contain 0's for the intersection values. Report them
Time complexity:O(m+n)
Space complexity: O(1)
Find the size of the minimum length array, assume it's array1 size of n
- Anonymous April 19, 2011loop array1 1..n
if(BST(array2, array1[i) == true) add array1[i] to the set to return
O(nlogm)
with hashtable we can achieve O(n) with size O(m)