Very simple algorithm but somehow interviewers love this. So, here it is:
For example, if the input arrays are:
arr1[] = {1, 3, 4, 5, 7}
arr2[] = {2, 3, 5, 6}
Then your program should print Intersection as {3, 5}.
Algorithm:
For Intersection of two arrays, print the element only if the element is present in both arrays.
1) Use two index variables i and j, initial values i = 0, j = 0
2) If arr1[i] is smaller than arr2[j] then increment i.
3) If arr1[i] is greater than arr2[j] then increment j.
4) If both are same then print any of them and increment both i and j.
Code:
a1 = [1,3,4,5,7]
a2 = [2,3,5,6]
i,j = 0,0
#Get length of the larger array as the count
count = (max(len(a1), len(a2)))
for x in range(0,count):
if (a1[i] a2[j]):
j = j+1
elif (a1[i] == a2[j]):
print a1[i]
i = i+1
j = j+1