Dot Product of Two Sparse Vectors - Problem
Given two sparse vectors, compute their dot product. A sparse vector is a vector that has mostly zero values - think of it like a long list where only a few positions have meaningful data.
You need to implement a SparseVector class with:
SparseVector(nums)- Initializes the object with the vector numsdotProduct(vec)- Computes the dot product between this instance and vec
The dot product is calculated by multiplying corresponding elements and summing the results: v1[0]*v2[0] + v1[1]*v2[1] + ... + v1[n]*v2[n]
Key Challenge: Store the sparse vector efficiently and compute the dot product optimally. Since most values are zero, we don't want to waste time or space on them!
Follow-up: What if only one of the vectors is sparse?
Input & Output
example_1.py โ Basic sparse vectors
$
Input:
nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
โบ
Output:
8
๐ก Note:
v1 = [1,0,0,2,3], v2 = [0,3,0,4,0]. Dot product = 1ร0 + 0ร3 + 0ร0 + 2ร4 + 3ร0 = 0 + 0 + 0 + 8 + 0 = 8
example_2.py โ Highly sparse vectors
$
Input:
nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
โบ
Output:
0
๐ก Note:
No overlapping non-zero positions. All products are 0, so dot product = 0
example_3.py โ Dense vectors
$
Input:
nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4]
โบ
Output:
6
๐ก Note:
Only position 4 has non-zero values in both: 2ร3 = 6
Constraints
- n == nums1.length == nums2.length
- 1 โค n โค 105
- -100 โค nums1[i], nums2[i] โค 100
- At most 1000 calls will be made to dotProduct
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Problem
Most vector elements are zero, wasting computation time
2
Store Smart
Use hash map to store only meaningful (non-zero) values
3
Compute Efficiently
Only process indices that have values in both vectors
Key Takeaway
๐ฏ Key Insight: For sparse data, only store and process the meaningful elements. This transforms an O(n) problem into O(k) where k << n, providing massive speedups for highly sparse vectors.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code