For two vectors and
, the dot product
.
- If
or
,
does not play a role in the dot product.
- The order of sum does not matter.
So, we represent a sparse vector as a map of nonzero values: {index -> value}. While computing dot product, we iterate over the vector that has a shorter sparse representation.
Say len(nums) = and only
values are nonzero.
| Operation | Time | Space |
__init__ | ||
dotProduct |
class SparseVector:
def __init__(self, nums: List[int]):
self.data = {i: val for i, val in enumerate(nums) if val != 0}
# Return the dotProduct of two sparse vectors
def dotProduct(self, vec: "SparseVector") -> int:
short_vec, long_vec = (
(self.data, vec.data)
if len(self.data) <= len(vec.data)
else (vec.data, self.data)
)
dot = 0
for i, elem in short_vec.items():
if i in long_vec:
dot += ( elem * long_vec[i] )
return dot
# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)
Follow up: What if only one of the vectors is sparse?
We would still pick the sparse vector as the shorter of the two and iterate over it.
Leave a comment