Meta Interview Question

A code for dot product of two sparse vectors.

Interview Answer

Anonymous

Jul 13, 2018

100% accurate and efficient. I wrote the code on one of those shared screens. def sparse_dot_product(vec1, vec2): """ input: vec1 and vec2 list of tuples representing sparse vectors outut: the dot product of the two vectors. """ len1 = len(vec1) len2 = len(vec2) if (len1==0) or (len2==0): raise ValueError('One of the vectors is empty!') pointer1 = 0 pointer2 = 0 product = 0 while (pointer1 < len1) and (pointer2 < len2): if vec1[pointer1][0] == vec2[pointer2][0]: product += (vec1[pointer1][1] * vec2[pointer2][1]) pointer1 += 1 pointer2 += 1 elif vec1[pointer1][0] < vec2[pointer2][0]: pointer1 += 1 elif vec2[pointer2][0] < vec1[pointer1][0]: pointer2 += 1 return product

1