Dot Product of Two Sparse Vectors - Problem
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 ofSparseVectorandvec
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?
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
›
Output:
8
💡 Note:
Dot product = 1×0 + 0×3 + 0×0 + 2×4 + 3×0 = 0 + 0 + 0 + 8 + 0 = 8
Example 2 — All Zeros
$
Input:
nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
›
Output:
0
💡 Note:
No overlapping non-zero elements: 0×0 + 1×0 + 0×0 + 0×0 + 0×2 = 0
Example 3 — Same Position Non-Zero
$
Input:
nums1 = [0,1,0,0,2,0], nums2 = [1,0,0,0,3,0]
›
Output:
6
💡 Note:
Only position 4 has non-zero in both: 0×1 + 1×0 + 0×0 + 0×0 + 2×3 + 0×0 = 6
Constraints
- n == nums1.length == nums2.length
- 1 ≤ n ≤ 105
- 0 ≤ nums1[i], nums2[i] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Sparse Vectors
Two vectors with mostly zero values
2
Store Non-Zero Only
Extract and store only non-zero elements with indices
3
Compute Dot Product
Find overlapping indices and multiply corresponding values
Key Takeaway
🎯 Key Insight: Store only non-zero elements to skip unnecessary multiplications by zero and save memory
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code