Sparse Vector Dot Product
MediumHash Map · Meta
You are given two integer vectors nums1 and nums2 of the same length n. Return their dot product: the sum of nums1[i] * nums2[i] over every index i.
Both vectors are sparse, meaning most of their entries are 0. A zero entry contributes nothing to the sum, so instead of walking every index, aim to store only the non-zero entries (for example as index -> value pairs) and multiply only at positions where *both* vectors are non-zero.
In the original version of this problem each vector is wrapped in a SparseVector object that is built once and then dotted against many other vectors. Here you receive both arrays in one call, but design your representation as if it would be reused for many dot products.
Return the result as an integer. Do not modify the input arrays.
Example 1
- Input:
- nums1 = [0, 4, 0, 0, 3, 0], nums2 = [2, 5, 0, 0, -1, 0]
- Output:
- 17
- Explanation
- Only indices 1 and 4 are non-zero in both vectors:
4 * 5 + 3 * (-1) = 20 - 3 = 17. Index 0 is non-zero only innums2, so it contributes nothing.
Example 2
- Input:
- nums1 = [0, 0, 6, 0], nums2 = [1, 0, 0, 8]
- Output:
- 0
- Explanation
nums1is non-zero only at index 2 andnums2only at indices 0 and 3, so no index has a non-zero value in both.
Example 3
- Input:
- nums1 = [3, 0, -2], nums2 = [3, 0, -2]
- Output:
- 13
- Explanation
3 * 3 + (-2) * (-2) = 9 + 4 = 13.
Constraints
nums1.length == nums2.length == n1 <= n <= 10^5-100 <= nums1[i], nums2[i] <= 100- Most entries are
0