How to find the intersection of two sorted arrays
Intersection of two sorted arrays
Given two sorted arrays, finding their intersection involves returning the elements that appear in both of them. For example, the intersection of the arrays,
Solution
Since the arrays are sorted, we can simply iterate through both of them simultaneously using different loop counters. While doing so, we can do an element-wise comparison in both arrays, and if both elements are the same, the elements can be added to the intersection (if it hasn't already been added before). However, if the elements are not the same, the counter of one of the arrays is incremented (depending on which element was greater). The whole process is repeated until one of the arrays has been completely traversed. This process is depicted below with an example:
Example
def sortedArrayIntersection(arr1, arr2):counter1 = 0counter2 = 0intersection = []while (1):if(counter1 >= len(arr1) or counter2 >= len(arr2)): # as soon as one of the arrays has been completely traversed, return the intersectionreturn intersectionif arr1[counter1] == arr2[counter2]: # element exists in both arraysif counter1 == 0 or arr1[counter1] != arr1[counter1 - 1]: # checking if the current element is equal to the previous element (to avoid duplicates)intersection.append(arr1[counter1])# increment both counterscounter1 += 1counter2 += 1elif arr1[counter1] < arr2[counter2]:counter1 += 1else:counter2 += 1arr1 = [2, 15]arr2 = [3, 3, 7, 15, 31]print(sortedArrayIntersection(arr1, arr2))
Explanation
The sortedArrayIntersection() function highlighted in the code above is explained below:
Lines 6–8: We use
counter1to iterate througharr1. We usecounter2to iterate througharr2. This is done until one of the counters exceeds the length of the array it is traversing, in which case we returnintersection.Lines 10–12: If
arr1[counter1] == arr2[counter2], check whether this element is a duplicate (by comparing it with the previous element of one of the arrays). If it isn't a duplicate, add it to theintersectionand incrementcounter1andcounter2.Lines 18–22: If
arr1[counter1] > arr2[counter2], incrementcounter2(the arrays are sorted, so the next value inarr2will be greater than or equal to the current one). Otherwise, incrementcounter1.
Time complexity
Since this solution only involves traversing through each of the
Free Resources