Common Elements in Sorted Arrays

Given two sorted arrays, find the common elements between them in O(n+m) time with constant space.

The Idea: Maintain two iterators for two arrays. If the number at one of the iterators exceeds the other number at the second iterator, then increment the iterator in the other number. In the next step, this iterator will be >= the previous number and potentially match next the number that was greater than it in the previous step. The same applies in reverse. Once any of iterators exceed there current list, there are no longer any elements in common so the algorithm terminates.

def common_elements(ar1, ar2):
    iter1, iter2 = 0, 0
    common = []
    while iter1 < len(ar1) and iter2 < len(ar2):
        if ar1[iter1] == ar2[iter2]:
            common.append(ar1[iter1])
            iter1 += 1
            iter2 += 1
        elif ar1[iter1] > ar2[iter2]:
            iter2 += 1
        else:
            iter1 += 1

    return common


ar1 = [1, 3, 4, 6, 7, 8]
ar2 = [1, 2, 4, 5, 9, 10]
print(common_elements(ar1, ar2))

ar1 = [1,2,3,4,5,6]
ar2 = [4,5,6]
print(common_elements(ar1, ar2))

ar1 = []
ar2 = [4,5,6]
print(common_elements(ar1, ar2))

ar1 = [2,4,6,8]
ar2 = [1,2,8,10]
print(common_elements(ar1, ar2))

Last updated