Dot Product of Two Sparse Vectors
Given two sparse vectors represented as arrays, compute their dot product efficiently.
A sparse vector has mostly zero elements. Store only non-zero elements for efficiency.
Example
1,0,0,2,3 0,3,0,4,0
8
- The inputs are two vectors of the same length 5: and . Most entries are zero, which is what makes them sparse.
- The dot product is , one product per position.
- A position contributes something only when both entries are non-zero. is non-zero at positions 0, 3 and 4; is non-zero at positions 1 and 3. The only shared position is 3.
- Every other term vanishes: at position 0, ; at position 1, ; at position 4, .
- So , a single integer, which is the output
8. - Notice that if the two vectors had no non-zero position in common, the answer would be no matter how large their values were.
Constraints
- 1 <= len(nums1) == len(nums2) <= 10^5
- 0 <= nums[i] <= 100