Dot Product of Two Sparse Vectors Problem
Description
LeetCode Problem 1570.
Given two sparse vectors, compute their dot product.
Implement class SparseVector:
SparseVector(nums)Initializes the object with the vectornumsdotProduct(vec)Compute the dot product between the instance of SparseVector andvec
A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector.
Follow up: What if only one of the vectors is sparse?
Example 1:
Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
Output: 8
Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8
Example 2:
Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
Output: 0
Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0
Example 3:
Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4]
Output: 6
Constraints:
n == nums1.length == nums2.length1 <= n <= 10^50 <= nums1[i], nums2[i] <= 100
Solution
Approach: Store Only the Nonzero Entries
A product term a[i] * b[i] is zero unless both entries are nonzero, so the zeros carry no information. Store each vector as a hash map from index to value, keeping only the nonzero entries.
To compute the dot product, walk the map with fewer entries and look each index up in the other map. Indices missing from the other map contribute nothing.
Walking the smaller map also answers the follow-up: if only one vector is sparse, the work is proportional to the number of nonzeros in that sparse vector, no matter how dense the other one is. (An alternative is to store sorted (index, value) lists and merge them with two pointers, which avoids hashing but costs the sum of both lengths.)
Complexity: O(n) time to build a vector, and O(min(k1, k2)) time for a dot product, where k1 and k2 are the numbers of nonzero entries. Each vector uses O(k) space.
class SparseVector:
def __init__(self, nums: List[int]):
# index -> value, for the nonzero entries only
self.nonzero = {i: x for i, x in enumerate(nums) if x != 0}
# Return the dotProduct of two sparse vectors
def dotProduct(self, vec: 'SparseVector') -> int:
a, b = self.nonzero, vec.nonzero
if len(b) < len(a):
a, b = b, a # walk the vector with fewer nonzeros
return sum(x * b.get(i, 0) for i, x in a.items())
# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)